How to use the compile function from nunjucks

Find comprehensive JavaScript nunjucks.compile code examples handpicked from public code repositorys.

nunjucks.compile is a function in the Nunjucks templating engine that compiles a template into a JavaScript function that can be used to render the template with dynamic data.

55
56
57
58
59
60
61
62
63
        })
      }
    }

    const env = new Nunjucks.Environment(loader, options.compile)
    const template = Nunjucks.compile(doc.body.data.toString(), env, doc.file.path)
    return Promise.resolve(template)
  }
}
fork icon2
star icon2
watch icon0

57
58
59
60
61
62
63
64
65
  // hexo.log.info(logname, 'compile', data.path);
  logs.compile.push(data.path);
  writefile(logfile, JSON.stringify(logs, null, 2));

  // hexo.log.info(logname, 'text' in data ? data.text : data.path);
  const compiled = nunjucks.compile('text' in data ? data.text : fs.readFileSync(data.path), env);

  return compiled.render.bind(compiled);
}
fork icon1
star icon2
watch icon1

+ 15 other calls in file

How does nunjucks.compile work?

In the Nunjucks templating engine, nunjucks.compile is a function that takes a template string as input and compiles it into a JavaScript function that can be used to render the template with dynamic data. The resulting function can then be called with a data context object to produce a rendered output. The nunjucks.compile function works by parsing the template string and converting it into an abstract syntax tree (AST), which represents the structure and logic of the template. It then generates JavaScript code from the AST that can be evaluated to render the template with the specified data context. The resulting compiled function takes two arguments: the first argument is a data context object that provides values for the dynamic variables in the template, and the second argument is an options object that provides configuration options for rendering the template. Here's an example implementation of nunjucks.compile that demonstrates how the function works: javascript Copy code {{{{{{{ const nunjucks = require('nunjucks'); const templateString = 'Hello, {{ name }}!'; const compiledTemplate = nunjucks.compile(templateString); const context = { name: 'Alice' }; const renderedOutput = compiledTemplate.render(context); console.log(renderedOutput); In this example, we first import the nunjucks templating engine. We then define a template string templateString that includes a dynamic variable name. We call nunjucks.compile(templateString) to compile the template into a JavaScript function compiledTemplate. We can then call compiledTemplate.render(context) to render the template with the specified data context context. The rendered output is then assigned to renderedOutput and logged to the console. Overall, nunjucks.compile provides a powerful way to generate dynamic content in HTML, emails, and other types of documents. By allowing you to define templates with dynamic variables and compile them into JavaScript functions, Nunjucks provides a flexible and efficient way to generate dynamic content with ease.

48
49
50
51
52
53
54
55
56
57
function compile(data) {
    // hexo.log.info(logname, 'compile', data.path);
    logs.compile.push(data.path);
    writefile(logfile, JSON.stringify(logs, null, 2));
    // hexo.log.info(logname, 'text' in data ? data.text : data.path);
    var compiled = nunjucks.compile('text' in data ? data.text : fs.readFileSync(data.path), env);
    return compiled.render.bind(compiled);
}
// hexo Renderer API implicitly requires 'compile' to be a value of the rendering function
render.compile = compile;
fork icon1
star icon2
watch icon1

+ 14 other calls in file

238
239
240
241
242
243
244
245
246
247
.src('**/*.njk', { cwd: __dirname, ignore: ['**/*.content.njk', '_*.njk'].concat(globalIgnore) })
.pipe(
	through2.obj((file, _enc, next) => {
		if (file.isDirectory() || file.isNull()) return next();
		if (file.extname === '.njk') {
			const template = nunjucks.compile(fs.readFileSync(file.path, 'utf-8'), env);
			const render = template.render({});
			fs.writeFileSync(file.path.replace(/.njk$/, '.html'), render);
		}
		next();
fork icon0
star icon2
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
const nunjucks = require("nunjucks");

const templateString = "Hello, {{ name }}!";
const compiledTemplate = nunjucks.compile(templateString);

const context = { name: "Alice" };
const renderedOutput = compiledTemplate.render(context);

console.log(renderedOutput);

In this example, we first import the nunjucks templating engine. We then define a template string templateString that includes a dynamic variable name. We call nunjucks.compile(templateString) to compile the template into a JavaScript function compiledTemplate. We can then call compiledTemplate.render(context) to render the template with the specified data context context. The rendered output is then assigned to renderedOutput and logged to the console. Overall, nunjucks.compile provides a powerful way to generate dynamic content in HTML, emails, and other types of documents. By allowing you to define templates with dynamic variables and compile them into JavaScript functions, Nunjucks provides a flexible and efficient way to generate dynamic content with ease.

26
27
28
29
30
31
32
33
34
35
36
    if (typeof dictionary !== 'undefined' && dictionary !== null) {
      return pangu.spacing(dictionary);
    }
    return '""';
  });
  return nunjucks.compile(data.text, env, data.path);
}


function njkRenderer(data, locals) {
  return njkCompile(data).render(locals);
fork icon0
star icon0
watch icon1

+ 5 other calls in file

7
8
9
10
11
12
13
14
15
16
17
  
  const tpl_paths = await fg('templates/*.tpl', {cwd: __dirname});
  for (let tpl of tpl_paths) {
    const pathInfo = path.parse(tpl);
    const content = await fs.readFile(path.resolve(__dirname, tpl), 'utf-8');
    templates[pathInfo.name] = nunjucks.compile(content);
  }


  return templates;
};
fork icon0
star icon0
watch icon1

+ 3 other calls in file

52
53
54
55
56
57
58
59
60
61
62
63
64
  }
  nunjucksAddFilter(env);


  const text = 'text' in data ? data.text : readFileSync(data.path);


  return nunjucks.compile(text, env, data.path);
}


function njkRenderer(data, locals) {
  return njkCompile(data).render(locals);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

7
8
9
10
11
12
13
14
15
16
var query = loaderUtils.getOptions(this) || {};
var exportsString = "module.exports = ";
let template;
// 如果只是需要进行模版变异
if(query.precompile){
  template = nunjucks.compile(source).tmplStr;
  template = template.replace(/\\"/g, "\\\\\"");
  template = template.replace(/\\'/g, "\\\\\'");
  template = compile('`' + template + '`').code;
  return exportsString + template;
fork icon0
star icon0
watch icon0

201
202
203
204
205
206
207
208
209
210
}

async compile(str, inputPath) {
  let tmpl;
  if (!inputPath || inputPath === "njk" || inputPath === "md") {
    tmpl = NunjucksLib.compile(str, this.njkEnv);
  } else {
    tmpl = NunjucksLib.compile(str, this.njkEnv, inputPath);
  }
  return async function(data) {
fork icon0
star icon0
watch icon0

+ 5 other calls in file