Skip to content

v2 HTML with CSS or JavaScript

axunonb edited this page Feb 6, 2022 · 1 revision

A frequent question being asked is: We get errors when using Smart.Format with a format string that contains HTML with CSS and/or JavaScript included.

While processing pure HTML works absolutely fine, the result becomes unpredictable with CSS and/or JavaScript. The reason is obvious: Smart.Format uses braces to identify Placeholders, which are at the same time part of the CSS/JavaScript notation.

You may get the desired results, when setting Settings.ParseErrorAction = ErrorAction.MaintainTokens, or you may not. Please have a look at the unit tests

Even slight changes to the format string influence the result. It's unreliable.

Therefore, it is strongly recommended to pre-process HTML with CSS/JavaScript using the AngleSharp library. The following sample shows that only three extra lines of code will help. Note: The example assumes, that CSS/JavaScript is located outside the <body>tag.

using AngleSharp;

var html = @"
<html>
    <head>
        <script>
            (function() {
                var ep;
                var loginState;
                try {
                    window.localStorage && (ep = JSON.parse(window.localStorage.getItem('dl_ep') || 'false'));
                window.localStorage && (loginState = JSON.parse(window.localStorage.getItem('dl_loginState')) || undefined);
            } catch(e) {
                console.error(e);
            }
        </script>
        <style type='text/css'>
            .site-sticky-top {
                position: -webkit-sticky;
                position: sticky;
                top: 0;
                z-index: 1020;
            }
        </style>
    </head>
    <body>
        <div class='main'>
            My name is {Name}. I'm living in {City}.
        </div>
    </body>
</html>
";

var variables = new { Name = "John Long", City = "New York" };

// Create a new parser front-end (can be re-used)
var parser = new AngleSharp.Html.Parser.HtmlParser();

// Get the DOM representation
AngleSharp.Html.Dom.IHtmlDocument htmlDocument = parser.ParseDocument(html);

// ##### Smart.Format the HTML body: #####
htmlDocument.Body.InnerHtml = Smart.Format(htmlDocument.Body.InnerHtml, variables);

// This gets the complete HTML as a string
var result = htmlDocument.ToHtml();
Clone this wiki locally