Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Last active July 24, 2017 14:34
Show Gist options
  • Save Ugarz/63ad3df6dd1acd2cf3147cad8670c996 to your computer and use it in GitHub Desktop.
Save Ugarz/63ad3df6dd1acd2cf3147cad8670c996 to your computer and use it in GitHub Desktop.
Templating a file with Lodash

Discover the advanced templating function with lodash

Moar informations here at the Lodash documentation

Create a file index.js and copy paste it. Do not forget to

npm init -y &&
npm i lodash fs nodemon -D

Paste this into the index.js

You can now node index.js or user nodemon index.js (if you have it globally or locally) and tweak the isVerso variable true < > false.

const template = require('lodash/template');
const templateSettings = require('lodash/templateSettings');
const fs = require('fs');

const isVerso = true;
const templateFile = isVerso ? fs.readFileSync('./templateRectoVerso.tpl', 'utf-8') : fs.readFileSync('./templateRecto.tpl', 'utf-8');
const rawDatas = {
  recto: {
    name: 'toto',
    age: 42
  }
};

const addVerso = obj => Object.assign({}, rawDatas, obj);

const dto = { verso: { name: 'tata', age: 19 } };
const templating = template(templateFile);
if (isVerso) {
  const finalDatas = addVerso(dto);
  console.log('\n FinalDatas', finalDatas);
  console.log('\n Templating', templating(finalDatas));
} else {
  console.log('\n FinalDatas', rawDatas);
  console.log('\n Templating', templating(rawDatas));
}


// Use custom template delimiters.
templateSettings.interpolate = /{{([\s\S]+?)}}/g;
const compiled = template('hello {{ user }}!');

console.log('\n COMPILED', compiled({ user: 'mustache' }));

// FinalDatas { recto: { name: 'toto', age: 42 },
//   verso: { name: 'tata', age: 19 } }
// 
//  Templating <name>toto</name>
// <name>tata</requestDate>
// 
//  COMPILED hello mustache!

In a file templateRecto.tpl

<name><%= recto.name %></name>

In a file templateRectoVerso.tpl

<name><%= recto.name %></name>
<name><%= verso.name %></name>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment