Home

Awesome

twig-loader Build Status

Webpack loader for compiling Twig.js templates. This loader will allow you to require Twig.js views to your code.

Installation

npm install twig-loader

Usage

Webpack 2 and later

Documentation: Using loaders

module.exports = {
  //...

  module: {
    rules: [
      {
        test: /\.twig$/,
        use: {
          loader: 'twig-loader',
          options: {
              // See options section below
          },
        }
      }
    ]
  },

  node: {
      fs: "empty" // avoids error messages
  }
};

Webpack 1

Documentation: Using loaders


module.exports = {
    //...

    module: {
        rules: [
            {
                test: /\.twig$/,
                loader: "twig-loader",
                options: {
                    // See options section below
                },
            }
        ]
    },

    node: {
        fs: "empty" // avoids error messages
    }
};

Options

Loading templates

{# File: dialog.html.twig #}
<p>{{title}}</p>
// File: app.js
var template = require("dialog.html.twig");
// => returns pre-compiled template as a function and automatically includes Twig.js to your project

var html = template({title: 'dialog title'});
// => Render the view with the given context

When you extend another view, it will also be added as a dependency. All twig functions that refer to additional templates are supported: import, include, extends & embed.

Dynamic templates and registering at runtime

twig-loader will only resolve static paths in your templates, according to your webpack configuration. When you want to use dynamic templates or aliases, they cannot be resolved by webpack, and will be left untouched in your template. It is up to you to make sure those templates are available in Twig at runtime by registering them yourself:

var twig = require('twig').twig
twig({
  id: 'your-custom-template-id,
  data: '<p>your template here</p>',
  allowInlineIncludes: true,
  rethrow: true
});

Or more advanced when using webpack.context:

var twig = require('twig').twig

var context = require.context('./templates/', true, /\.twig$/)
context.keys().forEach(key => {
  var template = context(key);
  twig({
    id: key, // key will be relative from `./templates/`
    data: template.tokens, // tokens are exported on the template function
    allowInlineIncludes: true,
    rethrow: true
  });
});

Changelog

0.4.1 / 2018-06-12

0.4.0 / 2018-05-17

0.3.1 / 2017-11-08

0.3.0 / 2017-02-19

0.2.4 / 2016-12-29

0.2.3 / 2016-06-11

0.2.2 / 2016-06-03

0.2.1 / 2016-04-18

0.2.0 / 2016-01-21