Gathering detailed insights and metrics for posthtml-expressions
Gathering detailed insights and metrics for posthtml-expressions
Gathering detailed insights and metrics for posthtml-expressions
Gathering detailed insights and metrics for posthtml-expressions
npm install posthtml-expressions
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
123 Stars
343 Commits
20 Forks
7 Watching
2 Branches
17 Contributors
Updated on 15 Oct 2024
Minified
Minified + Gzipped
JavaScript (87.56%)
HTML (12.44%)
Cumulative downloads
Total Downloads
Last day
-14.8%
3,585
Compared to previous day
Last week
0.4%
20,588
Compared to previous week
Last month
13%
86,130
Compared to previous month
Last year
-17.1%
1,059,520
Compared to previous year
1npm i -D posthtml-expressions
1const { readFileSync } = require('fs') 2 3const posthtml = require('posthtml') 4const expressions = require('posthtml-expressions') 5 6posthtml(expressions({ locals: { foo: 'bar' } })) 7 .process(readFileSync('index.html', 'utf8')) 8 .then((result) => console.log(result.html))
This plugin provides a syntax for including local variables and expressions in your templates, and also extends custom tags to act as helpers for conditionals and looping.
You have full control over the delimiters used for injecting locals, as well as the tag names for the conditional and loop helpers, if you need them. All options that can be passed to the expressions
plugin are shown below:
Option | Default | Description |
---|---|---|
delimiters | ['{{', '}}'] | Array containing beginning and ending delimiters for escaped locals os expressions |
unescapeDelimiters | ['{{{', '}}}'] | Array containing beginning and ending delimiters for unescaped locals |
locals | {} | Object containing any local variables you want to be available inside your expressions |
localsAttr | locals | Attribute name for the tag script which contains locals |
removeScriptLocals | false | Will remove tag script which contains locals |
conditionalTags | ['if', 'elseif', 'else'] | Array containing names for tags used for if/else statements |
switchTags | ['switch', 'case', 'default'] | Array containing names for tags used for switch/case/default statements |
loopTags | ['each'] | Array containing names for for loops |
scopeTags | ['scope'] | Array containing names for scopes |
ignoredTag | 'raw' | String containing name of tag inside which parsing is disabled |
strictMode | true | Boolean value set to false will not throw an exception if a value in locals not found or expression could not be evaluated |
missingLocal | undefined | string defining the replacement value in case value not found in locals. May contain {expression} placeholder |
You can inject locals into any piece of content in your html templates, other than overwriting tag names. For example, if you passed the following config to the expressions plugin:
1locals: { className: 'intro', name: 'Marlo', 'status': 'checked' }
1<div class="{{ className }}"> 2 <input type="radio" {{ status }}> 3 My name is {{ name }} 4</div>
1<div class="intro"> 2 <input type="radio" checked=""> 3 My name is Marlo 4</div>
You can also use the script tag with the attribute locals
or you custome attribute containing data to interpolate in the template.
1<script locals> 2 module.exports = { 3 name: 'Scrum' 4 } 5</script> 6 7<div>My name: {{name}}</div>
1<script locals> 2 module.exports = { 3 name: 'Scrum' 4 } 5</script> 6 7<div>My name: Scrum</div>
In addition, the use of script tag allow you to use locals
defined globally to assign data to variables.
1posthtml(expressions({ locals: { foo: 'bar' } })) 2 .process(readFileSync('index.html', 'utf8')) 3 .then((result) => console.log(result.html))
1<script locals> 2 module.exports = { 3 name: 'Scrum', 4 foo: locals.foo || 'empty' 5 } 6</script> 7 8<div>My name: {{name}}</div> 9<div>Foo: {{foo}}</div>
1<script locals> 2 module.exports = { 3 name: 'Scrum', 4 foo: locals.foo || 'empty' 5 } 6</script> 7 8<div>My name: {{name}}</div> 9<div>Foo: bar</div>
What to produce in case of referencing a value not in locals
can be configured by the missingLocal
and strictMode
options.
When strictMode
is true (default) and leaving the missingLocal
option undefined
, then "'foo' is not defined" exception is thrown.
Setting strictMode
false and leaving the missingLocal
option undefined
results the string undefined
in the output
Setting the option missingLocal
to a string will produce that string in the output regardless the value of option strictMode
. missingLocal
can contain the placeholder {local}
which will be replaced with the name of the missing local in the output. This solution allows to:
missingLocal
to ""
locals
like "#Missing value: {local}"missingLocal | strictMode | output |
---|---|---|
undefined (default) | true (default) | Error is thrown |
undefined (default) | false | 'undefined' |
'' | false /true | '' (not output) |
{local} | false /true | original reference like {{foo}} |
By default, special characters will be escaped so that they show up as text, rather than html code. For example, if you had a local containing valid html as such:
1locals: { statement: '<strong>wow!</strong>' }
1<p>The fox said, {{ statement }}</p>
1<p>The fox said, <strong>wow!<strong></p>
In your browser, you would see the angle brackets, and it would appear as intended. However, if you wanted it instead to be parsed as html, you would need to use the unescapeDelimiters
, which by default are three curly brackets, like this:
1<p>The fox said, {{{ strongStatement }}}</p>
In this case, your code would render as html:
1<p>The fox said, <strong>wow!<strong></p>
You are not limited to just directly rendering local variables either, you can include any type of javascript expressions and it will be evaluated, with the result rendered. For example:
1<p class="{{ env === 'production' ? 'active' : 'hidden' }}">in production!</p>
With this in mind, it is strongly recommended to limit the number and complexity of expressions that are run directly in your template. You can always move the logic back to your config file and provide a function to the locals object for a smoother and easier result. For example:
1locals: { 2 isProduction: (env) => env === 'production' ? 'active' : 'hidden' 3}
1<p class="{{ isProduction(env) }}">in production!</p>
Many JavaScript frameworks use {{
and }}
as expression delimiters. It can even happen that another framework uses the same custom delimiters you have defined in this plugin.
You can tell the plugin to completely ignore an expression by prepending @
to the delimiters:
1<p>The @{{ foo }} is strong with this one.</p>
Result:
1<p>The {{ foo }} is strong with this one.</p>
Conditional logic uses normal html tags, and modifies/replaces them with the results of the logic. If there is any chance of a conflict with other custom tag names, you are welcome to change the tag names this plugin looks for in the options. For example, given the following config:
1locals: { foo: 'foo' }
1<if condition="foo === 'bar'"> 2 <p>Foo really is bar! Revolutionary!</p> 3</if> 4 5<elseif condition="foo === 'wow'"> 6 <p>Foo is wow, oh man.</p> 7</elseif> 8 9<else> 10 <p>Foo is probably just foo in the end.</p> 11</else>
1<p>Foo is probably just foo in the end.</p>
Anything in the condition
attribute is evaluated directly as an expressions.
It should be noted that this is slightly cleaner-looking if you are using the SugarML parser. But then again so is every other part of html.
1if(condition="foo === 'bar'") 2 p Foo really is bar! Revolutionary! 3 4elseif(condition="foo === 'wow'") 5 p Foo is wow, oh man. 6 7else 8 p Foo is probably just foo in the end.
conditionalTags
Type: array
Default: ['if', 'elseif', 'else']
You can define custom tag names to use for creating a conditional.
Example:
1conditionalTags: ['when', 'elsewhen', 'otherwise']
1<when condition="foo === 'bar'"> 2 <p>Foo really is bar! Revolutionary!</p> 3</when> 4 5<elsewhen condition="foo === 'wow'"> 6 <p>Foo is wow, oh man.</p> 7</elsewhen> 8 9<otherwise> 10 <p>Foo is probably just foo in the end.</p> 11</otherwise>
Note: tag names must be in the exact order as the default ones.
Switch statements act like streamline conditionals. They are useful for when you want to compare a single variable against a series of constants.
1locals: { foo: 'foo' }
1<switch expression="foo"> 2 <case n="'bar'"> 3 <p>Foo really is bar! Revolutionary!</p> 4 </case> 5 <case n="'wow'"> 6 <p>Foo is wow, oh man.</p> 7 </case> 8 <default> 9 <p>Foo is probably just foo in the end.</p> 10 </default> 11</switch>
1<p>Foo is probably just foo in the end.</p>
Anything in the expression
attribute is evaluated directly as an expressions.
switchTags
Type: array
Default: ['switch', 'case', 'default']
You can define custom tag names to use when creating a switch.
Example:
1switchTags: ['clause', 'when', 'fallback']
1<clause expression="foo"> 2 <when n="'bar'"> 3 <p>Foo really is bar! Revolutionary!</p> 4 </when> 5 <when n="'wow'"> 6 <p>Foo is wow, oh man.</p> 7 </when> 8 <fallback> 9 <p>Foo is probably just foo in the end.</p> 10 </fallback> 11</clause>
Note: tag names must be in the exact order as the default ones.
You can use the each
tag to build loops. It works with both arrays and objects. For example:
1locals: { 2 array: ['foo', 'bar'], 3 object: { foo: 'bar' } 4}
Array
1<each loop="item, index in array"> 2 <p>{{ index }}: {{ item }}</p> 3</each>
1<p>1: foo</p> 2<p>2: bar</p>
Object
1<each loop="value, key in anObject"> 2 <p>{{ key }}: {{ value }}</p> 3</each>
1<p>foo: bar</p>
The value of the loop
attribute is not a pure expressions evaluation, and it does have a tiny and simple custom parser. Essentially, it starts with one or more variable declarations, comma-separated, followed by the word in
, followed by an expressions.
1<each loop="item in [1,2,3]"> 2 <p>{{ item }}</p> 3</each>
So you don't need to declare all the available variables (in this case, the index is skipped), and the expressions after in
doesn't need to be a local variable, it can be any expressions.
loopTags
Type: array
Default: ['each']
You can define custom tag names to use for creating loops:
Example:
1loopTags: ['each', 'for']
You can now also use the <for>
tag when writing a loop:
1<for loop="item in [1,2,3]"> 2 <p>{{ item }}</p> 3</for>
Inside a loop, you have access to a special loop
object, which contains information about the loop currently being executed:
loop.index
- the current iteration of the loop (0 indexed)loop.remaining
- number of iterations until the end (0 indexed)loop.first
- boolean indicating if it's the first iterationloop.last
- boolean indicating if it's the last iterationloop.length
- total number of itemsExample:
1<each loop='item in [1,2,3]'> 2 <li>Item value: {{ item }}</li> 3 <li>Current iteration of the loop: {{ loop.index }}</li> 4 <li>Number of iterations until the end: {{ loop.remaining }} </li> 5 <li>This {{ loop.first ? 'is' : 'is not' }} the first iteration</li> 6 <li>This {{ loop.last ? 'is' : 'is not' }} the last iteration</li> 7 <li>Total number of items: {{ loop.length }}</li> 8</each>
You can replace locals inside certain area wrapped in a <scope>
tag. For example you can use it after posthtml-include
1locals: { 2 author: { name: 'John'}, 3 editor: { name: 'Jeff'} 4}
1<scope with="author"> 2 <include src="components/profile.html"></include> 3</scope> 4<scope with="editor"> 5 <include src="components/profile.html"></include> 6</scope>
1<div class="profile"> 2 <div class="profile__name">{{ name }}</div> 3 <img class="profile__avatar" src="{{ image }}" alt="{{ name }}'s avatar" /> 4 <a class="profile__link" href="{{ link }}">more info</a> 5</div>
scopeTags
Type: array
Default: ['scope']
You can define a custom tag name to use for creating scopes:
Example:
1scopeTags: ['context']
You can now also use the <context>
tag when writing a scope:
1<context with="author"> 2 <include src="components/profile.html"></include> 3</context>
Anything inside this tag will not be parsed, allowing you to output delimiters and anything the plugin would normally parse, in their original form.
1<raw> 2 <if condition="foo === 'bar'"> 3 <p>Output {{ foo }} as-is</p> 4 </if> 5</raw>
1<if condition="foo === 'bar'"> 2 <p>Output {{ foo }} as-is</p> 3</if>
You can customize the name of the tag:
1var opts = { 2 ignoredTag: 'verbatim', 3 locals: { foo: 'bar' } } 4} 5 6posthtml(expressions(opts)) 7 .process(readFileSync('index.html', 'utf8')) 8 .then((result) => console.log(result.html))
1<verbatim> 2 <if condition="foo === 'bar'"> 3 <p>Output {{ foo }} as-is</p> 4 </if> 5</verbatim>
1<if condition="foo === 'bar'"> 2 <p>Output {{ foo }} as-is</p> 3</if>
Jeff Escalante |
Denis Malinochkin |
Michael Ciniawsky |
Krillin |
Cosmin Popovici |
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
5 existing vulnerabilities detected
Details
Reason
Found 6/14 approved changesets -- score normalized to 4
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More