Get macro partials to insert JavaScript at bottom of body
Hi everyone, I'm putting this here in case anyone runs into the same issues I did.
I like my websites to have JavaScript at the bottom of the body. I typically include dependencies (such as jQuery) in the template, or allow users to add them through a document property. However it's been difficult to get macros to respect this structure -- if I ever wanted macros to include JavaScript (for a calendar widget, or image carousel), it had to be inserted inline with the macro content.
No more! I now have macro partials that place JavaScript where I want them.
Extension Method
First I created a new file under App_Code called ExtensionMethods.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
public static class ExtensionMethods
{
private const string SCRIPTBLOCK_BUILDER = "ScriptBlockBuilder";
public static MvcHtmlString MacroScriptBlock(this WebViewPage webPage, Func<dynamic, HelperResult> template)
{
if (!webPage.IsAjax)
{
var scriptBuilder = webPage.Context.Items[SCRIPTBLOCK_BUILDER] as StringBuilder ?? new StringBuilder();
scriptBuilder.Append(template(null).ToHtmlString());
webPage.Context.Items[SCRIPTBLOCK_BUILDER] = scriptBuilder;
return new MvcHtmlString(string.Empty);
}
return new MvcHtmlString(template(null).ToHtmlString());
}
public static MvcHtmlString MacroScriptBlocks(this WebViewPage webPage)
{
var scriptBuilder = webPage.Context.Items[SCRIPTBLOCK_BUILDER] as StringBuilder ?? new StringBuilder();
return new MvcHtmlString(scriptBuilder.ToString());
}
}
Get macro partials to insert JavaScript at bottom of body
Hi everyone, I'm putting this here in case anyone runs into the same issues I did.
I like my websites to have JavaScript at the bottom of the body. I typically include dependencies (such as jQuery) in the template, or allow users to add them through a document property. However it's been difficult to get macros to respect this structure -- if I ever wanted macros to include JavaScript (for a calendar widget, or image carousel), it had to be inserted inline with the macro content.
No more! I now have macro partials that place JavaScript where I want them.
Extension Method
First I created a new file under
App_Code
calledExtensionMethods.cs
:Template
Next I include the following in my template file:
Macro
Finally, here is an example of a macro partial,
FullCalendar.cshtml
:Sources
Thanks to the following sources:
is working on a reply...