Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundling CSS files depending on domain of request?

I have a multi-tenant application and I'm trying to determine the simplest means of controlling which CSS files are bundled based on the url of any incoming request.

I'm thinking I can have some conditional logic inside RegisterBundles() that takes the Url as a string, and bundles accordingly:

public static void RegisterBundles(BundleCollection bundles, string tenant = null) {
     if (tenant == "contoso"){
           bundles.Add(new StyleBundle("~/contoso.css") 
     }
}

But I don't know how to pass the string into RegisterBundles, nor even if it's possible, or the right solution. Any help here would be awesome.

like image 353
RobVious Avatar asked Nov 09 '13 01:11

RobVious


1 Answers

It is not possible to do it in RegisterBundles right now. Dynamically generating the bundle content per request will prevent ASP.net from caching the minified CSS (it's cached in HttpContext.Cache).

What you can do is create one bundle per tenant in RegisterBundles then select the appropriate bundle in the view.

Example code in the view:

@Styles.Render("~/Content/" + ViewBag.TenantName)

Edit:

As you said, setting the TenantName in a ViewBag is problematic since you have to do it per view. One way to solve this is to create a static function like Styles.Render() that selects the correct bundle name based from the current tenant.

public static class TenantStyles
{
    public static IHtmlString Render(params string[] paths)
    {
        var tenantName = "test"; //get tenant name from where its currently stored
        var tenantExtension = "-" + tenantName;
        return Styles.Render(paths.Select(i => i + tenantExtension).ToArray());
    }
}

Usage

@TenantStyles.Render("~/Content/css")

The bundle names will need to be in the this format {bundle}-{tenant} like ~/Content/css-test. But you can change the format ofcourse.

like image 164
LostInComputer Avatar answered Sep 29 '22 23:09

LostInComputer