Using sections in Editor/Display templates

后端 未结 8 956
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 17:15

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, M

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 17:40

    The answer given in Populate a Razor Section From a Partial using the RequireScript HtmlHelper follows the same pattern. It also has the benefit that it checks for and suppresses duplicate references to the same Javascript URL, and it has an explicit priority parameter that can be used to control ordering.

    I extended this solution by adding methods for:

    // use this for scripts to be placed just before the  tag
    public static string RequireFooterScript(this HtmlHelper html, string path, int priority = 1) { ... }
    public static HtmlString EmitRequiredFooterScripts(this HtmlHelper html) { ... }
    
    // use this for CSS links
    public static string RequireCSS(this HtmlHelper html, string path, int priority = 1) { ... }
    public static HtmlString EmitRequiredCSS(this HtmlHelper html) { ... }
    

    I like Darin's & eth0's solutions though since they use the HelperResult template, which allows for script and CSS blocks, not just links to Javascript and CSS files.

提交回复
热议问题