-
-
Notifications
You must be signed in to change notification settings - Fork 105
v2 HTML with CSS or JavaScript
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 Placeholder
s, 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
- for a JavaScript format string
- for a CSS format string
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();
- Syntax, Terminology
- Placeholders and Nesting
- string.Format Compatibility
- Character Literals in Format Strings
- HTML With CSS or JavaScript
- Data Source Extensions
- Default _ DefaultFormatter
- Lists _ ListFormatter
- Choose _ ChooseFormatter
- Condition _ ConditionalFormatter
- Null _ NullFormatter
- SubString _ SubStringFormatter
- RegEx _ IsMatchFormatter
- Pluralization _ PluralLocalizationFormatter
- Localization _ LocalizationFormatter
- Templates _ TemplateFormatter
- TimeSpan _ TimeFormatter
- XML _ XElementFormatter
- Extension Methods
- Home
- Common Pitfalls
- HTML with CSS or JavaScript
- Overview
- Main Features
- Formatters
- Extra Features
- Console and StringBuilder
- TemplateFormatter
- SmartSettings to control Smart.Format behavior
- Additional Info
- License