Skip to content

Instantly share code, notes, and snippets.

@gazlu
Last active October 20, 2015 10:19
Show Gist options
  • Save gazlu/65bc7c4345fa93655694 to your computer and use it in GitHub Desktop.
Save gazlu/65bc7c4345fa93655694 to your computer and use it in GitHub Desktop.
Create dynamic script and css bundles right from your views
//@Html.ScriptsBundle("~/bundles/ng-modules", "~/Scripts/vendor/ng/modules", true)
public static class DynamicBundles
{
public static IHtmlString StylesBundle(this HtmlHelper helper, string virtualPath, params string[] additionalPaths)
{
if (BundleTable.Bundles.GetBundleFor(virtualPath) == null)
{
BundleTable.Bundles.Add(new StyleBundle(virtualPath).Include(additionalPaths));
}
return MvcHtmlString.Create(@"<link href=""" + HttpUtility.HtmlAttributeEncode(BundleTable.Bundles.ResolveBundleUrl(virtualPath)) + @""" rel=""stylesheet""/>");
}
public static IHtmlString ScriptsBundle(this HtmlHelper helper, string virtualPath, params string[] additionalPaths)
{
if (BundleTable.Bundles.GetBundleFor(virtualPath) == null)
{
BundleTable.Bundles.Add(new ScriptBundle(virtualPath).Include(additionalPaths));
}
return MvcHtmlString.Create(@"<script src=""" + HttpUtility.HtmlAttributeEncode(BundleTable.Bundles.ResolveBundleUrl(virtualPath)) + @"""></script>");
}
public static IHtmlString StylesBundle(this HtmlHelper helper, string virtualPath, string directory, bool includeSubDirectories)
{
if (BundleTable.Bundles.GetBundleFor(virtualPath) == null)
{
BundleTable.Bundles.Add(new StyleBundle(virtualPath).IncludeDirectory(directory, "*.css", includeSubDirectories));
}
return MvcHtmlString.Create(@"<link href=""" + HttpUtility.HtmlAttributeEncode(BundleTable.Bundles.ResolveBundleUrl(virtualPath)) + @""" rel=""stylesheet""/>");
}
public static IHtmlString ScriptsBundle(this HtmlHelper helper, string virtualPath, string directory, bool includeSubDirectories)
{
if (BundleTable.Bundles.GetBundleFor(virtualPath) == null)
{
BundleTable.Bundles.Add(new ScriptBundle(virtualPath).IncludeDirectory(directory, "*.js", includeSubDirectories));
}
return MvcHtmlString.Create(@"<script src=""" + HttpUtility.HtmlAttributeEncode(BundleTable.Bundles.ResolveBundleUrl(virtualPath)) + @"""></script>");
}
}
@gazlu
Copy link
Author

gazlu commented Oct 20, 2015

Example
@Html.ScriptsBundle("/bundles/ng-modules", "/Scripts/vendor/ng/modules", true)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment