U
U
Uncle Vanya2019-04-09 13:32:44
JavaScript
Uncle Vanya, 2019-04-09 13:32:44

Does anyone know a simple and good template engine?

Hello dear.
There is such an idea:
For example, on the command line you enter something like "create galaxy"
And after that the galaxy folder is created in the directory specified in the config, with all the files necessary .... js, sass, html and so on, but the files are not empty, but already with the code copied from the blanks.
YoMan was not quite simple, and I did not find normal docks on it with simple examples.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ihor Bratukh, 2019-04-09
@QSem

Here's an example of a simple template engine that only knows how to replace variables, without if/else/for...

const file = `
  <template>
    <div>
      #{hello}
      Component #{component.name} working!
    </div>
  </template>

  <script>
    export default {
      name: '#{component.name}'
    }
  </script>
`;

const output = templater(file, {
  hello: 'Hello from templater function',
  component: {
    name: "My Default Component Name"
  }
});

console.log(output);

function templater(input, data, config) {
  const setup = Object.assign({}, {
    flag: 'g',
    start: '\#\{',
    end: '\}',
    deep: true
  }, config);

  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      if (setup.deep && (typeof data[key] === "object" && data[key] !== null && !Array.isArray(data[key]))) {
        const deep = {};
        for (const name in data[key]) {
          if (Object.prototype.hasOwnProperty.call(data[key], name)) {
            deep[`${key}.${name}`] = data[key][name];
          }
        }
        input = templater(input, deep, setup);
      } else {
        input = input.replace(new RegExp(setup.start + key + setup.end, setup.flag), data[key]);
      }
    }
  }

  return input;
}

B
bqio, 2019-04-09
@bqio

git clone (repurl)
:)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question