Skip to content

Commit

Permalink
Merge 08ebad5 into 1b67350
Browse files Browse the repository at this point in the history
  • Loading branch information
Scrum committed Aug 9, 2021
2 parents 1b67350 + 08ebad5 commit 028d0be
Show file tree
Hide file tree
Showing 8 changed files with 1,331 additions and 1,507 deletions.
9 changes: 6 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
'use strict'

const vm = require('vm')
const parser = require('posthtml-parser')
const render = require('posthtml-render')
const { parser } = require('posthtml-parser')
const { render } = require('posthtml-render')

const getNextTag = require('./tags')
const parseLoopStatement = require('./loops')
const escapeRegexpString = require('./escape')
const makeLocalsBackup = require('./backup').make
const revertBackupedLocals = require('./backup').revert
const placeholders = require('./placeholders')
const scriptDataLocals = require('./locals')

const delimitersSettings = []
let conditionals, switches, loops, scopes, ignored, delimitersReplace, unescapeDelimitersReplace
Expand Down Expand Up @@ -156,7 +157,9 @@ module.exports = function postHTMLExpressions (options) {

// kick off the parsing
return function (tree) {
return normalizeTree(clearRawTag(walk({ locals: options.locals, strictMode: options.strictMode }, tree)), tree.options)
const { locals } = scriptDataLocals(tree, options)

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

Expand Down
44 changes: 44 additions & 0 deletions lib/locals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use strict'

const vm = require('vm')
const matchHelper = require('posthtml-match-helper')
const { render } = require('posthtml-render')

// const code = 'module.exports = {a: 1}';
const ctx = vm.createContext({ module })

// const r = vm.runInContext(code, ctx)

/**
* @description Get the script tag with locals attribute from a node list and return locals.
*
* @method scriptDataLocals
*
* @param {Array} tree Nodes
*
* @return {Object} {} Locals
*/
function scriptDataLocals (tree, options) {
const locals = {}
const localsAttr = options.localsAttr || 'locals'

tree.match(matchHelper(`script[${localsAttr}]`), node => {
if (node.content) {
const code = render(node.content)

try {
const local = vm.runInContext(code, ctx)

Object.assign(locals, local)
} catch {};
}

return node
})

return {
locals
}
}

module.exports = scriptDataLocals
2,692 changes: 1,200 additions & 1,492 deletions package-lock.json

Large diffs are not rendered by default.

11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@
},
"dependencies": {
"fclone": "^1.0.11",
"posthtml-parser": "^0.6.0",
"posthtml-render": "^1.4.0"
"posthtml-match-helper": "^1.0.1",
"posthtml-parser": "^0.10.0",
"posthtml-render": "^3.0.0"
},
"devDependencies": {
"ava": "^3.13.0",
"jsdoc-to-markdown": "^6.0.1",
"ava": "^3.15.0",
"jsdoc-to-markdown": "^7.0.1",
"nyc": "^15.1.0",
"posthtml": "^0.15.1",
"posthtml": "^0.16.5",
"posthtml-beautify": "^0.7.0",
"standard": "^16.0.3",
"standard-changelog": "^2.0.27"
Expand Down
32 changes: 25 additions & 7 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![code style][style]][style-url]
[![chat][chat]][chat-url]

<div align="center">
<img width="110" height="100" title="PostHTML Plugin" vspace="50" src="http://michael-ciniawsky.github.io/postcss-load-plugins/logo.svg">
Expand Down Expand Up @@ -42,6 +40,7 @@ You have full control over the delimiters used for injecting locals, as well as
| **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 |
| **localsAttr** | `locals` | Attribute name for the 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 |
| **loopTags** | `['each']` | Array containing names for `for` loops |
Expand Down Expand Up @@ -71,6 +70,28 @@ locals: { className: 'intro', name: 'Marlo', 'status': 'checked' }
</div>
```

You can also use the script tag with the attribute `locals` or you custome attribute containing data to interpolate in the template.

```html
<script locals>
module.exports = {
name: 'Scrum'
}
</script>

<div>My name: {{name}}</div>
```

```html
<script locals>
module.exports = {
name: 'Scrum'
}
</script>

<div>My name: Scrum</div>
```

### Unescaped Locals

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:
Expand Down Expand Up @@ -503,14 +524,11 @@ posthtml(expressions(opts))
[deps]: https://david-dm.org/posthtml/posthtml-expressions.svg
[deps-url]: https://david-dm.org/posthtml/posthtml-expressions

[tests]: http://img.shields.io/travis/posthtml/posthtml-expressions.svg
[tests-url]: https://travis-ci.org/posthtml/posthtml-expressions
[tests]: https://github.com/posthtml/posthtml-expressions/workflows/Actions%20Status/badge.svg?style=flat-square
[tests-url]: https://github.com/posthtml/posthtml-expressions/actions?query=workflow%3A%22CI+tests%22

[cover]: https://coveralls.io/repos/github/posthtml/posthtml-expressions/badge.svg
[cover-url]: https://coveralls.io/github/posthtml/posthtml-expressions

[style]: https://img.shields.io/badge/code%20style-standard-yellow.svg
[style-url]: http://standardjs.com/

[chat]: https://badges.gitter.im/posthtml/posthtml.svg
[chat-url]: https://gitter.im/posthtml/posthtml?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"
7 changes: 7 additions & 0 deletions test/expect/script-locals.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script locals="">
module.exports = {
name: 'Scrum'
}
</script>

<div>My name: Scrum</div>
7 changes: 7 additions & 0 deletions test/fixtures/script-locals.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script locals>
module.exports = {
name: 'Scrum'
}
</script>

<div>My name: {{name}}</div>
36 changes: 36 additions & 0 deletions test/test-locals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const test = require('ava')

const join = require('path').join
const readSync = require('fs').readFileSync

const posthtml = require('posthtml')
const expressions = require('../lib')

const fixture = (file) => {
return readSync(join(__dirname, 'fixtures', `${file}.html`), 'utf8')
}

const expect = (file) => {
return readSync(join(__dirname, 'expect', `${file}.html`), 'utf8')
}

function process (t, name, options, log = false, plugins = [expressions(options)], processOptions = {}) {
return posthtml(plugins)
.process(fixture(name), processOptions)
.then((result) => {
log && console.log(result.html)

return clean(result.html)
})
.then((html) => {
t.is(html, expect(name).trim())
})
}

function clean (html) {
return html.replace(/[^\S\r\n]+$/gm, '').trim()
}

test('Basic', (t) => {
return process(t, 'script-locals')
})

0 comments on commit 028d0be

Please sign in to comment.