Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* Template string as function.
*
* Pros: Only has access to parameters.
* Cons: Have to make a module.
*/
import {template} from './template-string-as-function.js';
let page = template({
title: "10 Wierd Template String Tricks",
post: "blah blah blah",
author: "Anonymous"
});
/* Eval template string.
*
* Pros: template string is a simple string.
* Cons: template string has access to local variables.
*/
import {readFileSync} from 'fs';
let title = "10 Wierd Template String Tricks",
post = "blah blah blah",
author = "Anonymous";
let page = eval('`' + readFileSync('./template-string-as-file.txt') + '`');
/* New Template String eval method.
*
* Pros: Relatively safe, tempalte string can be a separate file.
* Cons:
*/
import {readFileSync} from 'fs';
let page = String.evalTemplate(readFileSync('./template-string-as-file.txt'), {
title: "10 Wierd Tricks",
post: "blah blah blah",
author: "Anonymous"
});
/* Other possible solutions:
*
* - eval that only allows a template string.
* - eval that only allows a tempalte string with substitutions that don't run code.
*/
<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
</head>
<body>
<h1>${title}</h1>
<p>By ${author}</p>
<article>${post}</article>
</body>
</html>
export const template ({title, post, author}) =>
`<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
</head>
<body>
<h1>${title}</h1>
<p>By ${author}</p>
<article>${post}</article>
</body>
</html>`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.