How to use the nunjucks.Loader 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 unic / darvin-webpack-boilerplate / webpack / libs / nunjucks-loader.js View on Github external
/**
* based on: https://github.com/ryanhornberger/nunjucks-html-loader
* bind specific context
* edit by Darvin
*/

const utils = require('loader-utils');
const fs = require('fs-extra');
const path = require('path');
const nunjucks = require('nunjucks');
const crypto = require('crypto');

let devServer = require('./devserver-storage');
let cacheRegister = {};

const NunjucksLoader = nunjucks.Loader.extend({
  init(searchPaths, sourceFoundCallback) {
    this.sourceFoundCallback = sourceFoundCallback;

    if (searchPaths) {
      searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];
      // For windows, convert to forward slashes
      this.searchPaths = searchPaths.map(path.normalize);
    } else {
      this.searchPaths = ['.'];
    }
  },

  getSource(name) {
    let fullpath = null;
    const paths = this.searchPaths;
github patrickarlt / acetate / lib / mixins / nunjucks.js View on Github external
module.exports = function (acetate) {
  function customTagError (name, type, e) {
    var error = acetate.util.parseException(e);
    e.message = util.format('error in custom %s "%s" - %s:%d:%d', type, name, error.path, error.lineNo, error.colNo);
    return e;
  }

  var Loader = nunjucks.Loader.extend({
    getSource: function (name) {
      acetate.debug('nunjucks', 'searching for templates named %s', name);

      var matches = glob.sync(name + '.+(html|md|markdown)', {
        cwd: path.join(acetate.src)
      });

      acetate.debug('nunjucks', 'found %d template(s) matching %s', matches.length, name);

      if (matches && matches[0]) {
        var fullpath = path.join(acetate.src, matches[0]);

        acetate.debug('nunjucks', 'loading %s', fullpath);

        return {
          src: fs.readFileSync(fullpath, 'utf-8').split(/^([\s\S]+)^-{3}$/m)[0],
github patrickarlt / acetate / lib / Renderer.js View on Github external
const minimatch = require("minimatch");
const async = require("async");
const _ = require("lodash");
const glob = require("glob");
const MarkdownIt = require("markdown-it");
const hljs = require("highlight.js");
const normalizeNewline = require("normalize-newline");
const Helper = require("./custom-tags/Helper.js");
const Block = require("./custom-tags/Block.js");
const CustomHelperError = require("./error-types/CustomHelperError.js");
const PageRenderError = require("./error-types/PageRenderError.js");
const TemplateNotFoundError = require("./error-types/TemplateNotFoundError.js");
const Logger = require("./Logger.js");
const EventEmitter = require("events");

const Loader = nunjucks.Loader.extend({
  init: function({ sourceDir, logger, errorHandler }) {
    this.sourceDir = sourceDir;
    this.logger = logger;
    this.errorHandler = errorHandler;
  },

  getSource: function(name) {
    this.logger.debug(`looking up templates ${name}, ${name}.md, ${name}.html`);

    const matches = glob.sync(`${name}?(.html|.md|)`, {
      cwd: this.sourceDir
    });

    if (!matches || !matches.length) {
      throw new TemplateNotFoundError(name);
    }
github frctl / fractal / src / engines / nunjucks.js View on Github external
/**
 * Module dependencies.
 */

var nunjucks      = require('nunjucks');
var _             = require('lodash');

var NotFoundError = require('../errors/notfound');

var viewCache = {};

var StringLoader = nunjucks.Loader.extend({
    getSource: function(name) {
        var view = _.find(viewCache, function(view){
            return (view.handle === name || view.alias === name);
        });
        if (view) {
            return {
                src: view.content,
                path: view.path,
                noCache: true
            };
        }
        throw new NotFoundError('Partial template not found.');
    }
});

var nj = new nunjucks.Environment(new StringLoader(), {
github patrickarlt / acetate / lib / acetate-nunjucks-loader.js View on Github external
var _ = require('lodash');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
var gaze = require('gaze');
var minimatch = require('minimatch');
var acetateUtils = require('./utils');
var nunjucks  = require('nunjucks');

module.exports = nunjucks.Loader.extend({
  init: function(options){
    this.templates = options.templates;
  },
  getSource: function(name){
    if(!name) {
      return null;
    }

    var matches = glob.sync(name + '.+(html|md|markdown)', {
      cwd: this.templates
    });

    if(matches && matches[0]){
      var fullpath = path.join(this.templates, matches[0]);
      return {
        src: acetateUtils.parseBody(fs.readFileSync(fullpath, 'utf-8')),
github frctl / fractal / packages / pages / src / render / env.js View on Github external
module.exports = function (templates, opts = {}) {
  const TemplateLoader = nunjucks.Loader.extend({
    getSource: function (path) {
      path = slash(path);
      debug(`Looking for Nunjucks template ${path}`);
      const file = templates.find(file => slash(file.relative) === path);
      if (file) {
        return {
          src: file.contents.toString(),
          path,
          noCache: true
        };
      }
    }
  });

  let env = new nunjucks.Environment(new TemplateLoader());
github frctl / fractal / packages / fractal-engine-nunjucks / src / engine.js View on Github external
module.exports = function (config = {}) {
  const loaders = [].concat(config.loaders || []);
  const exts = [].concat(config.ext || ['.njk', '.nunjucks', '.nunj']);

  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]);
github frctl / fractal / packages / internals / funjucks / src / env.js View on Github external
const loaders = (opts.loaders || []).map(loader => {
    if (loader instanceof nunjucks.Loader) {
      return loader;
    }
    if (_.isString(loader)) {
      return new nunjucks.FileSystemLoader(loader);
    }
    if (_.isPlainObject(loader)) {
      return new (nunjucks.Loader.extend(loader))();
    }
    throw new Error(`Funjucks - Unknown loader type`);
  });
github frctl / fractal / src / render.js View on Github external
'use strict';

const Promise     = require('bluebird');
const nunjucks    = require('nunjucks');
const _           = require('lodash');
const highlighter = require('./highlighter');
const Component   = require('./components/component');
const Variant     = require('./components/variant');
const Page        = require('./pages/page');
const context     = require('./components/context');
const status      = require('./components/status');
const app         = require('./app');
const logger      = require('./logger');

const NullLoader = nunjucks.Loader.extend({
    getSource: name => {}
});

module.exports = function (includePath, config) {

    config = config || {};

    const loader = includePath ? new nunjucks.FileSystemLoader(includePath, {
        watch: false,
        noCache: true
    }) : new NullLoader();

    const env = Promise.promisifyAll(new nunjucks.Environment(loader, {
        autoescape: false,
        noCache: true
    }));