How to inline css when getting page from TemplateContext

Is it possible to get htmlstring with inlined CSS as output from the templateContext?
My code looks something like the below:

using (var context = new TemplateContext().Init())
{
    context.VirtualFiles.WriteFile("_layout.html", File.ReadAllText("_layout.html"));
    context.VirtualFiles.WriteFile("myCss.css", File.ReadAllText("myCss.css"));
    context.VirtualFiles.WriteFile("page.html", File.ReadAllText("myPage.html"));
           
    var pageResult = new PageResult(context.GetPage("page"));
    var htmlString = await pageResult.RenderToStringAsync();
}

The layout file:

<html>
    <head>
        <title></title>
        <link rel="stylesheet" type="text/css" href="myCss.css">
    </head>
    <body>
       {{ page }}
    </body>
</html>

I want the the link tag to be replaced by the css styles in myCss.css inside style tags.

Minification never happens inside Templates, it’s normally done by Webpack, parcel or node js libraries directly as part of the bundling solution but if you want to do this in C# you can use the built-in HTML, CSS and JS minifiers:

context.VirtualFiles.WriteFile("myCss.css", 
    Minifiers.Css.Compress(File.ReadAllText("myCss.css")));

I see, my usecase is to generate pdf documents from the html and css files. If the templatecontext could output the html with inlined css, it would be nice to have.

The TemplateContext is a general purpose dynamic Templating language that generates text verbatim, it doesn’t have any notion of HTML inside the language nor should it do any HTML transforms like inline minification. My above comment shows how to minimize CSS yourself, you can either add the CSS already minified or run the generated HTML through the HTML minifier with Minifiers.HtmlAdvanced.Compress(html) but this behaviour should not be in the language itself.

1 Like