How to add JS and CSS to all content parts in an Orchard module

500 views Asked by At

I am writing a module for Orchard CMS 1.8.1

I would like to add custom styles to all content parts that I have written for the module. I need these to work regardless of the theme chosen by the website admins. I could add links to the CSS and JS files in every view file for every content part - but that seems messy and prone to future bugs - what's the best way to have a single file that loads up the styles needed for all my content parts?

Should I provide a different Content.cshtml that includes the links? This also seems like it could be problematic if the admins need their own control over the main Content.cshtml

Many thanks

1

There are 1 answers

1
Xeevis On BEST ANSWER

Handler should do the trick, I wrote this from the top of my head so not sure if it really works.

First create ResourceManifest.cs and define your stylesheets and scripts

public class ResourceManifest : IResourceManifestProvider
{
    public void BuildManifests(ResourceManifestBuilder builder)
    {
        var manifest = builder.Add();
        manifest.DefineStyle("MyStylesheet").SetUrl("mystylesheet.min.css", "mystylesheet.css").SetVersion("1.0.0");
        manifest.DefineScript("MyScript").SetUrl("myscript.min.js", "myscript.js").SetVersion("1.0.0");
    }
}

Then it should be enough to create content handler and override the BuildDisplayShape

public class MyResourceHandler : ContentHandler
{
    private readonly Work<IResourceManager> _resourceManager;

    public MyResourceHandler(Work<IResourceManager> resourceManager)
    {
        _resourceManager = resourceManager;
    }

    protected override void BuildDisplayShape(BuildDisplayContext context)
    {
        if (context.DisplayType == "Detail" && context.ContentItem.Has(typeof(MyPart)))
        {
            this._resourceManager.Value.Require("stylesheet", "MyStylesheet");
            this._resourceManager.Value.Require("script", "MyScript");
        }

        base.BuildDisplayShape(context);
    }
}

Adjust the IF as necessary. And let me know if it works ;)

Beauty of using ResourceManifest with versioning is that anyone can replace your stylesheets/javascript with their own just by defining style in their own ResourceManifest (module/theme) with same name and higher version number and don't have to touch any original files.