Skip to content

Instantly share code, notes, and snippets.

@thomasfoster96
Created September 14, 2015 00:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasfoster96/193e7c08aae499f810a1 to your computer and use it in GitHub Desktop.
Save thomasfoster96/193e7c08aae499f810a1 to your computer and use it in GitHub Desktop.
/* 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