2

I am using requireJS for my hybrid app . Now I need to change the script tag located into my layout page with conditions on url . The script tag looks something like this

<script data-main="@Url.Content("~/Scripts/main")" src="@Url.Content("~/Scripts/Libs/Requirejs/require.min.js")" type="text/javascript"></script>

Now when the page loads the /Home/Login the script tag above should be changed to

<script data-main="@Url.Content("~/Scripts/login")" src="@Url.Content("~/Scripts/Libs/Requirejs/require.min.js")" type="text/javascript"></script>

Again when I load the page /Mail/Index The script tag above should change to

<script data-main="@Url.Content("~/Scripts/mail")" src="@Url.Content("~/Scripts/Libs/Requirejs/require.min.js")" type="text/javascript"></script>

Now Note that All of the three pages uses the same **_Layout.cshtml** page . And the above script tag is located in **_Layout.cshtml** page only .Now how do I track this scripts to change the script tag on change of the Url routing as mentioned above ?

1 Answer 1

2

I'd simply use a section for this. In the layout page:

@RenderSection("RequireScripts")

And put the script in each page:

@section RequireScripts {
    <script data-main="@Url.Content("~/Scripts/main")" src="@Url.Content("~/Scripts/Libs/Requirejs/require.min.js")" type="text/javascript"></script>
}

If you're after a way to avoid re-writing the whole thing (only requiring the relative path), then I suppose you could make use of the dynamic Page variable:

@if (Page.RequireScript != null)
{
    <script src='~/Scripts/@Page.RequireScript'></script>
}

Then the script block would get output to pages that define RequireScript.

@{
    Page.RequireScript = "Libs/Requirejs/require.min.js";
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks the 2nd soluton seems to be much more elegant . But there are two queries . In <script src='~/Scripts/@Page.RequireScript'></script> is @Page.Requirescript is a variable or is it an Mvc feature itself ? 2nd is Can i use any variable in that section which might lead to render into data-main attribute from the child page ?
@Joy it's a variable, not a feature of MVC itself. Page is a dynamic object, so you can throw whatever properties you want into it. For your second question, I don't quite understand, would you mind rephrasing?
Thats alright . I got what I wanted . your answer gave the point which i actually needed :) thanks bro :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.