ryanhornberger / nunjucks-html-loader

Webpack Loader for Nunjucks that returns raw html. Also works with Webpack watching system.
MIT License
27 stars 23 forks source link

add query options for nunjucks.configure #1

Open tapthoppe opened 8 years ago

tapthoppe commented 8 years ago

need a bit more config options, such as autoescape, trimBlocks, tags https://mozilla.github.io/nunjucks/api.html#configure

ryanhornberger commented 8 years ago

@ertle hey man, at the moment I'm not putting much work into this but if you have a change you'd like to submit you are welcome to. The LOC on this is pretty small.

jeremyzahner commented 7 years ago

@ertle I might have some time to invest in the future. For now we'd happily accept a PR containing the missing features.

goldfinch commented 7 years ago

Hey guys, thanks for the nice work on this loader.

I was needing to include some custom data from json file to be able to use it in nunjucks templates. Someone might find it useful for own purposes as well. I created a pull request to achieve this goal in case if you find it useful to have.

HermannBjorgvin commented 5 years ago

I created a local patch for this issue that seems to be working for me.

This is what the loader looks like set up.

/* Nunjucks loader */
const nunjucksOptions = {
  configure: function(env){
    markdown.register(env, marked);
  },
  searchPaths: basePath + '/src/html',
  context: {
    config: {
      'env': 'development',
      'image_src': '../../assets/images/'
    }
  }
};

config.module
    .rule('nunjucks')
    .test(/\.(njk|nunjucks)$/)
    .use('html-loader')
    .loader('html-loader')
    .end()
    .use('nunjucks-html-loader')
    .loader('nunjucks-html-loader')
    .options(nunjucksOptions);

I added two lines into index.js to support this. This will probably fault with a type error if you skip the configuration option. So it's probably best to enclose the nunjucksConfiguration function in an if typeof statement.

module.exports = function(content) {
    this.cacheable();

    var callback = this.async();
    var opt = utils.parseQuery(this.query);

    var nunjucksSearchPaths = opt.searchPaths;
    var nunjucksContext = opt.context;
    var nunjucksConfiguration = opt.configure;

    var loader = new NunjucksLoader(nunjucksSearchPaths, function(path) {
        this.addDependency(path);
    }.bind(this));

    var nunjEnv = new nunjucks.Environment(loader);
    nunjucks.configure(null, { watch: false });

    nunjucksConfiguration(nunjEnv);

    var template = nunjucks.compile(content, nunjEnv);
    html = template.render(nunjucksContext);

    callback(null, html);
};