Using sections in Editor/Display templates

后端 未结 8 954
爱一瞬间的悲伤
爱一瞬间的悲伤 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:30

    Modified version of Darin's answer to ensure ordering. Also works with CSS:

    public static IHtmlString Resource(this HtmlHelper HtmlHelper, Func Template, string Type)
    {
        if (HtmlHelper.ViewContext.HttpContext.Items[Type] != null) ((List>)HtmlHelper.ViewContext.HttpContext.Items[Type]).Add(Template);
        else HtmlHelper.ViewContext.HttpContext.Items[Type] = new List>() { Template };
    
        return new HtmlString(String.Empty);
    }
    
    public static IHtmlString RenderResources(this HtmlHelper HtmlHelper, string Type)
    {
        if (HtmlHelper.ViewContext.HttpContext.Items[Type] != null)
        {
            List> Resources = (List>)HtmlHelper.ViewContext.HttpContext.Items[Type];
    
            foreach (var Resource in Resources)
            {
                if (Resource != null) HtmlHelper.ViewContext.Writer.Write(Resource(null));
            }
        }
    
        return new HtmlString(String.Empty);
    }
    

    You can add JS and CSS resources like this:

    @Html.Resource(@, "js")
    @Html.Resource(@, "css")
    

    And render JS and CSS resources like this:

    @Html.RenderResources("js")
    @Html.RenderResources("css")
    

    You could do a string check to see if it starts with script/link so you don't have to explicitly define what each resource is.

提交回复
热议问题