Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added missingLocal option to define how to handle missing local value #138

Merged
merged 2 commits into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,15 @@ module.exports = function postHTMLExpressions (options) {
return function (tree) {
const { locals } = scriptDataLocals(tree, options)

return normalizeTree(clearRawTag(walk({ locals: { ...options.locals, ...locals }, strictMode: options.strictMode }, tree)), tree.options)
return normalizeTree(
clearRawTag(
walk(
{
locals: { ...options.locals, ...locals },
strictMode: options.strictMode,
missingLocal: options.missingLocal
}, tree)
), tree.options)
}
}

Expand Down
15 changes: 11 additions & 4 deletions lib/placeholders.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,20 @@ function placeholders (input, ctx, settings, opts) {
value = ctx[expression]
}

// Not found local
if (value === null || value === undefined) {
if (opts.missingLocal === undefined) {
if (opts.strictMode) {
throw new ReferenceError(`'${expression}' is not defined`)
}
} else if (typeof opts.missingLocal === 'string') {
value = opts.missingLocal.replace('{local}', match)
}
}
// Escape html if necessary
if (settings[i].escape && typeof value === 'string') {
value = escapeHTML(value)
}

// Stringify if value object
if (typeof value === 'object') {
} else if (typeof value === 'object') { // Stringify if value object
value = JSON.stringify(value)
}

Expand Down
32 changes: 25 additions & 7 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,18 @@ You have full control over the delimiters used for injecting locals, as well as

|Option|Default|Description|
|:----:|:-----:|:----------|
| **delimiters** | `['{{', '}}']` | Array containing beginning and ending delimiters for escaped locals |
| **unescapeDelimiters** | `['{{{', '}}}']` | Array containing beginning and ending delimiters for unescaped locals |
| **locals** | `{}` | Object containing any local variables you want to be available inside your expressions |
| **delimiters** | `['{{', '}}']` | Array containing beginning and ending delimiters for escaped locals os [expressions](#expressions) |
| [**unescapeDelimiters**](#unescaped-locals) | `['{{{', '}}}']` | Array containing beginning and ending delimiters for unescaped locals |
| [**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](#locals)***|
| **removeScriptLocals** | `false` | Will remove tag `script` which contains ***[locals](#locals)***|
| **conditionalTags** | `['if', 'elseif', 'else']` | Array containing names for tags used for `if/else if/else` statements |
| **switchTags** | `['switch', 'case', 'default']` | Array containing names for tags used for `switch/case/default` statements |
| [**conditionalTags**](#conditionals) | `['if', 'elseif', 'else']` | Array containing names for tags used for [*`if/else` statements*](#conditionals) |
| [**switchTags**](#switchtags) | `['switch', 'case', 'default']` | Array containing names for tags used for [*`switch/case/default` statements*](#switch-statement) |
| **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 |
| [**ignoredTag**](#ignored-tag) | `'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**](#missing-locals) | `undefined` | string defining the replacement value in case value not found in locals. May contain `{expression}` placeholder|

### Locals

Expand Down Expand Up @@ -124,6 +125,23 @@ posthtml(expressions({ locals: { foo: 'bar' } }))
<div>My name: {{name}}</div>
<div>Foo: bar</div>
```
#### Missing locals
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:
1. Silently ignore missing locals by setting `missingLocal` to `""`
2. Include the name of the missing local in the output to help detect the which value is missing in `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}}`

### Unescaped Locals

Expand Down
1 change: 1 addition & 0 deletions test/expect/local_missing.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>undefined<b>undefined</b></p>
1 change: 1 addition & 0 deletions test/expect/local_missing_keep.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>{{foo}}</p>
1 change: 1 addition & 0 deletions test/expect/local_missing_remove.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p><b></b></p>
1 change: 1 addition & 0 deletions test/expect/local_missing_replace.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>Error: {{foo}} undefined</p>
1 change: 1 addition & 0 deletions test/fixtures/local_missing.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>{{foo}}<b>{{foo? "bar": ""}}</b></p>
1 change: 1 addition & 0 deletions test/fixtures/local_missing_keep.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>{{foo}}</p>
1 change: 1 addition & 0 deletions test/fixtures/local_missing_remove.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>{{foo}}</p>
1 change: 1 addition & 0 deletions test/fixtures/local_missing_replace.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>{{foo}}</p>
26 changes: 24 additions & 2 deletions test/test-core.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ function process (t, name, options, log = false, plugins = [expressions(options)
})
}

function error (name, cb) {
return posthtml([expressions()])
function error (name, cb, opts) {
return posthtml([expressions(opts)])
.process(fixture(name))
.catch(cb)
}
Expand Down Expand Up @@ -103,3 +103,25 @@ test('Directives options', (t) => {
}]
})
})

test('local - missing - error', (t) => {
return error('local_missing', (err) => {
t.is(err.message, "'foo' is not defined")
})
})

test('local - missing - undefined', (t) => {
return process(t, 'local_missing', { strictMode: false })
})

test('local - missing - keep', (t) => {
return process(t, 'local_missing_keep', { missingLocal: '{local}' })
})

test('local - missing - keep / strictMode:false', (t) => {
return process(t, 'local_missing_keep', { missingLocal: '{local}', strictMode: false })
})

test('local - missing - replace', (t) => {
return process(t, 'local_missing_replace', { missingLocal: 'Error: {local} undefined' })
})