Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sections in Editor/Display templates

I want to keep all of my JavaScript code in one section; just before the closing body tag in my master layout page and just wondering the best to go about it, MVC style.

For example, if I create a DisplayTemplate\DateTime.cshtml file which uses jQuery UI's DateTime Picker than I would embed the JavaScript directly into that template but then it will render mid-page.

In my normal views I can just use @section JavaScript { //js here } and then @RenderSection("JavaScript", false) in my master layout but this doesn't seem to work in display/editor templates - any ideas?

like image 396
eth0 Avatar asked Mar 25 '11 14:03

eth0


1 Answers

You could proceed with a conjunction of two helpers:

public static class HtmlExtensions {     public static MvcHtmlString Script(this HtmlHelper htmlHelper, Func<object, HelperResult> template)     {         htmlHelper.ViewContext.HttpContext.Items["_script_" + Guid.NewGuid()] = template;         return MvcHtmlString.Empty;     }      public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)     {         foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)         {             if (key.ToString().StartsWith("_script_"))             {                 var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;                 if (template != null)                 {                     htmlHelper.ViewContext.Writer.Write(template(null));                 }             }         }         return MvcHtmlString.Empty;     } } 

and then in your _Layout.cshtml:

<body> ... @Html.RenderScripts() </body> 

and somewhere in some template:

@Html.Script(     @<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> ) 
like image 105
Darin Dimitrov Avatar answered Oct 09 '22 11:10

Darin Dimitrov