Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add JavaScript or css reference from an editor template

Let's say we had a scenario where our app was not going to use jqueryui, except for one particular editor template. If I want to avoid putting jqueryui onto every page (i.e. I don't want to include it in the bundle(s) that are loaded by default in my _Layout.cshtml), how could I have the editor template include the jqueryui.js and jqueryui.css files for me in a way that wouldn't result in multiple references to those files, and would put the references in the header or at the end of my body instead of inline?

Here's what I've tried in my editor template that didn't seem to work:

@System.Web.Optimization.Scripts.Render("~/bundles/jqueryui")
@System.Web.Optimization.Styles.Render("~/Content/jqueryuistyles")

This added the script and link tags, but it renders the tags once per use of the editor template, and it also renders them right in-line, so in my case, that's before jQuery has been loaded at the bottom of the body.

@section Scripts{ <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/jqueryui")"></script> }

This matches how I include the bundle in my _Layout.cshtml, but this apparently doesn't work from an editor template. Nothing was rendered at all, and even if it did, I think it'd still result in multiple references to the JavaScript file (1 per time that the editor template was called)

Seems like there should be a way to have an editor template trigger the inclusion of a JavaScript or css file that can tie into the bundles or at the very least the @section system. Anyone know how to do this?

like image 997
ctb Avatar asked Nov 27 '22 06:11

ctb


1 Answers

One way to accomplish this may be to request required javascript files using current request context. For example within Editor template you may write something like this to request a javascript include

HttpContext.Current.Items["Required.Script"] = "~/myeditortemplate.js";

Then in layout just before rendering of any optional script section you may render required script by looking at current context

Scripts.Render(HttpContext.Current.Items["Required.Script"].ToString())

Where Scripts is making use of script bundles in MVC. Alternativly you can simply emit script tag point src to required script.

like image 158
Mazhar Qayyum Avatar answered Jun 28 '23 14:06

Mazhar Qayyum