How to use the nunjucks.FileSystemLoader function in nunjucks

To help you get started, we’ve selected a few nunjucks examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github asyncapi / generator / lib / generator.js View on Github external
if (!templateName) throw new Error('No template name has been specified.');
    if (!entrypoint && !targetDir) throw new Error('No target directory has been specified.');
    if (!['fs', 'string'].includes(output)) throw new Error(`Invalid output type ${output}. Valid values are 'fs' and 'string'.`);

    this.templateName = templateName;
    this.targetDir = targetDir;
    this.templatesDir = templatesDir || DEFAULT_TEMPLATES_DIR;
    this.templateDir = path.resolve(this.templatesDir, this.templateName);
    this.templateParams = templateParams || {};
    this.entrypoint = entrypoint;
    this.noOverwriteGlobs = noOverwriteGlobs || [];
    this.disabledHooks = disabledHooks || [];
    this.output = output;

    // Config Nunjucks
    this.nunjucks = new Nunjucks.Environment(new Nunjucks.FileSystemLoader(this.templateDir));
    this.nunjucks.addFilter('log', console.log);
    this.loadTemplateConfig();
    this.registerHooks();
  }
github pangolinjs / core / lib / html / render-nunjucks.js View on Github external
return new Promise((resolve, reject) => {
    // Create Nunjucks environment
    let env = new nunjucks.Environment(
      new nunjucks.FileSystemLoader(path.join(context, 'src'))
    )

    // Prefix URL to make it relative
    env.addFilter('relative', (url) => {
      if (file.split(path.sep)[0] === 'components') {
        return `../${url}`
      } else {
        return url
      }
    })

    // Add custom section tag
    env.addExtension('SectionExtension', new SectionExtension())

    // Add environment variables to Nunjucks
    env.addGlobal('process', {
github mozilla / fxa / packages / fxa-content-server / server / bin / firefox_account_bridge.js View on Github external
function makeApp() {
  var app = express();
  var env = new nunjucks.Environment(
      new nunjucks.FileSystemLoader(
          path.join(__dirname, '..', 'views')));

  env.express(app);
  app.use(express.cookieParser());
  app.use(express.bodyParser());

  var isHttps = 'https' === urlparse(config.get('public_url')).scheme;

  // BigTent must be deployed behind SSL.
  // Tell client-sessions everything will be alright
  app.use(function(req, res, next) {
      req.connection.proxySecure = isHttps;
      next();
  });

  var sess_config = config.get('client_sessions');
github mozilla / thimble.mozilla.org / services / login.webmaker.org / app / http / server.js View on Github external
module.exports = function (env) {
  var express = require("express"),
    helmet = require("helmet"),
    i18n = require("webmaker-i18n"),
    lessMiddleWare = require("less-middleware"),
    WebmakerAuth = require("webmaker-auth"),
    nunjucks = require("nunjucks"),
    path = require("path"),
    route = require("./routes"),
    Models = require("../db")(env, newrelic).Models;

  var http = express(),
    nunjucksEnv = new nunjucks.Environment([
      new nunjucks.FileSystemLoader(path.join(__dirname, "views")),
      new nunjucks.FileSystemLoader(path.resolve(__dirname, "../../bower_components"))
    ], {
      autoescape: true
    }),
    messina,
    logger;

  var webmakerAuth = new WebmakerAuth({
    loginURL: env.get("APP_HOSTNAME"),
    authLoginURL: env.get("LOGINAPI"),
    loginHost: env.get("APP_HOSTNAME"),
    secretKey: env.get("SESSION_SECRET"),
    forceSSL: env.get("FORCE_SSL"),
    domain: env.get("COOKIE_DOMAIN"),
    allowCors: env.get("ALLOWED_CORS_DOMAINS") && env.get("ALLOWED_CORS_DOMAINS").split(" ")
  });
github cocopon / tweakpane / project / render-html-templates.js View on Github external
version: Package.version,
};

const SRC_DIR = 'src/doc/template';
const SRC_PATTERN = 'src/doc/template/*.html';
const DST_DIR = 'docs';

Fs.mkdirsSync(DST_DIR);

const srcPaths = Glob.sync(SRC_PATTERN).filter((path) => {
	return Path.basename(path).match(/^_.+$/) === null;
});
console.log(`Found sources: ${srcPaths.join(', ')}`);

const env = new Nunjucks.Environment(
	new Nunjucks.FileSystemLoader(SRC_DIR),
);

srcPaths.forEach((srcPath) => {
	const srcBase = Path.basename(srcPath);
	const dstPath = Path.join(DST_DIR, srcBase);
	Fs.writeFileSync(
		dstPath,
		env.render(srcBase, context),
	);
});

console.log('done.');
github calidion / vig / src / Templates / VTemplate.ts View on Github external
public getEnv() {
    if (this.initialized) {
      return this.env;
    }
    const views = this.getViews();
    const loader = new nunjucks.FileSystemLoader(views, {
      watch: true
    });
    const env = new nunjucks.Environment(loader, {
      autoescape: false
    });
    const filters = this.getFilters();
    for (const key of Object.keys(filters)) {
      env.addFilter(key, filters[key]);
    }
    this.env = env;
    this.initialized = true;
    return env;
  }
github frctl / fractal / packages / fractal-engine-nunjucks / src / engine.js View on Github external
let partials = {};
  const TemplateLoader = nunjucks.Loader.extend({
    getSource: function (lookup) {
      if (partials[lookup]) {
        return {
          src: partials[lookup].toString(),
          path: lookup,
          noCache: true
        };
      }
    }
  });

  if (config.views) {
    loaders.push(new nunjucks.FileSystemLoader(config.views));
  }

  const env = new nunjucks.Environment([new TemplateLoader(), ...loaders]);

  env.addExtension('WithExtension', new WithExtension());
  env.addExtension('IncludeWithExtension', new IncludeWithExtension());

  Object.keys(config.globals || {}).forEach(key => env.addGlobal(key, config.globals[key]));
  Object.keys(config.extensions || {}).forEach(key => env.addExtension(key, config.extensions[key]));
  if (Array.isArray(config.filters)) {
    config.filters.forEach(filter => env.addFilter(filter.name, filter.filter, filter.async));
  } else {
    Object.keys(config.filters || {}).forEach(key => env.addFilter(key, config.filters[key], config.filters[key].async));
  }

  return {
github michaelliao / itranswarp.js / www / middlewares / templating.js View on Github external
function createEnv(path, opts) {
    let
        autoescape = opts.autoescape === undefined ? true : opts.autoescape,
        noCache = opts.noCache || false,
        watch = opts.watch || false,
        throwOnUndefined = opts.throwOnUndefined || false,
        env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader(path, {
                noCache: noCache,
                watch: watch,
            }), {
                autoescape: autoescape,
                throwOnUndefined: throwOnUndefined
            }),
        f;
    if (opts.filters) {
        for (f in opts.filters) {
            env.addFilter(f, opts.filters[f]);
        }
    }
    return env;
}
github bigfix / developer.bigfix.com / site / build / lib / renderer.js View on Github external
function createTemplateEnv(templatesDir) {
  var loader = new nunjucks.FileSystemLoader(templatesDir, { watch: false });

  var templateEnv = new nunjucks.Environment(loader, { autoescape: true });

  templateEnv.addExtension('QNAExtension', createQNAExtension(templateEnv));
  templateEnv.addExtension('NoteExtension', createNoteExtension(templateEnv));
  templateEnv.addExtension('SectionExtension', createSectionExtension(templateEnv));
  templateEnv.addExtension('EvaluatorExtension', createEvaluatorExtension(templateEnv));
  templateEnv.addExtension('CollapseExtension', createCollapseExtension(templateEnv));
  templateEnv.addExtension('RESTAPIExtension', createRestApiExtension(templateEnv));

  templateEnv.addFilter('linkType', linkType);

  return templateEnv;
}
github mozilla / thimble.mozilla.org / server / templatize.js View on Github external
    paths.map(path => new Nunjucks.FileSystemLoader(path, nunjucksOptions))
  );