-
Notifications
You must be signed in to change notification settings - Fork 119
Using SquishIt programmatically without the file system
If your environment does not allow reading/writing to the file system, you may be ready to turn your back on SquishIt. Don't! It is entirely possible to use SquishIt programmatically.
The trick is to programmatically define your bundles in a Application_Bundle
method of your Global.asax file. You will call this method in Application_Start
and a special Application_BeginRequest
during DEBUG mode so will always have an up-to-date bundle (otherwise, if you change a file, SquishIt will not refresh your cache and you will not get any tags included in your markup).
protected void Application_Start() {
// ... everything else
// SquishIt
Application_Bundle();
}
protected void Application_Bundle() {
//SquishIt
Bundle.Css()
.Add("~/Content/Base.css")
.Add("~/Content/MainStyle.css")
.AsCached("main", "~/assets/css/main");
}
protected void Application_BeginRequest() {
#if DEBUG
// SquishIt adds a file cache dependency, so when the file changes
// locally, we should rebuild our bundle. This won't need to happen in Release mode.
Application_Bundle();
#endif
}
The key is the AsCached
method. The first argument is the name of your bundle (or key) and the next is the server URL SquishIt should use (the {id} is the key name, e.g. main
). As you can probably tell, we will need an AssetsController
in our project.
This is simple. If you are using the regular {id}
in MVC for your identifier arguments, simply create a new controller and inherit from SquishItController
.
However, if you are either using a custom BaseController or using a different name for the typical {id}
field (e.g. {identifier}
) you will need to copy the SquishItController code into your own controller. Be sure to specify that the content type is "text/css" for your CSS bundles. An example is below:
// could inherit directly from SquishItController but we use "identifier" as ID parameter in route not "id"
public class AssetsController : BaseController //: SquishItController
{
public ActionResult Js(string identifier)
{
return Content(Bundle.JavaScript().RenderCached(identifier));
}
public ActionResult Css(string identifier)
{
return Content(Bundle.Css().RenderCached(identifier), "text/css");
}
}
Almost done. Now you just need to render your scripts to your views. Luckily, it's one line of code!
@Bundle.CSS().MvcRenderCachedAssetTag("main")
@Bundle.JavaScript().MvcRenderCachedAssetTag("mainscripts")
You will need to import or set up the appropriate SquishIt namespace to use these in the views.