├── .eslintrc ├── .gitignore ├── .npmrc ├── .travis.yml ├── LICENSE ├── README.md ├── __specs__ ├── index.spec.js ├── mock.js └── templates │ ├── embed-base.twig │ ├── embed-ignore-missing.twig │ ├── embed-include.twig │ ├── embed-simple.twig │ ├── error-compile.twig │ ├── extendee.twig │ ├── extender.twig │ ├── from.twig │ ├── import.twig │ ├── include.twig │ ├── macro-self.twig │ ├── macro-wrapped.twig │ ├── macro.twig │ └── test.twig ├── examples ├── express │ ├── .gitignore │ ├── .npmrc │ ├── package.json │ ├── src │ │ ├── index.js │ │ └── views │ │ │ ├── index.twig │ │ │ └── layout.twig │ └── webpack.config.js ├── frontend │ ├── .gitignore │ ├── .npmrc │ ├── package.json │ ├── src │ │ ├── index.html │ │ └── js │ │ │ ├── index.js │ │ │ └── views │ │ │ ├── index.twig │ │ │ └── layout.twig │ └── webpack.config.js ├── namespaces │ ├── .gitignore │ ├── .npmrc │ ├── package.json │ ├── src │ │ ├── index.js │ │ └── views │ │ │ ├── include │ │ │ ├── head.twig │ │ │ └── layout.twig │ │ │ └── index.twig │ └── webpack.config.js └── typescript │ ├── .gitignore │ ├── .npmrc │ ├── package.json │ ├── src │ ├── index.ts │ └── views │ │ ├── index.twig │ │ └── layout.twig │ ├── tsconfig.json │ └── webpack.config.js ├── index.js ├── package.json └── typings ├── express.d.ts ├── index.d.ts └── twig.d.ts /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb-base/legacy", 3 | 4 | "parserOptions": { 5 | "ecmaVersion": 2018, 6 | "ecmaFeatures": { 7 | "experimentalObjectRestSpread": true 8 | } 9 | }, 10 | 11 | "env": { 12 | "node": true, 13 | "jasmine": true, 14 | "es6": true 15 | }, 16 | 17 | "rules": { 18 | "class-methods-use-this": 0, 19 | "comma-dangle": ["error", { 20 | "arrays": "always-multiline", 21 | "objects": "always-multiline", 22 | "imports": "always-multiline", 23 | "exports": "always-multiline", 24 | "functions": "never" 25 | }], 26 | "default-case": 0, 27 | "function-paren-newline": [0, "consistent"], 28 | "key-spacing": [2, { "mode": "minimum" }], 29 | "max-len": [1, 80], 30 | "no-await-in-loop": 0, 31 | "no-console": 0, 32 | "no-multi-spaces": [2, { "exceptions": { 33 | "Property": true, 34 | "VariableDeclarator": true, 35 | "AssignmentExpression": true, 36 | "ObjectExpression": true, 37 | "ClassProperty": true 38 | }}], 39 | "no-param-reassign": 0, 40 | "no-plusplus": 0, 41 | "no-restricted-syntax": [ 42 | "error", 43 | "LabeledStatement", 44 | "WithStatement" 45 | ], 46 | "no-underscore-dangle": 0, 47 | "no-unused-expressions": 0, 48 | "no-use-before-define": 0, 49 | "object-curly-newline": 0, 50 | "spaced-comment": [2, "always", { 51 | "line": { "markers": ["*package", "!", ",", "noinspection"] }, 52 | "block": { 53 | "balanced": true, 54 | "markers": ["*package", "!", ",", "noinspection"], 55 | "exceptions": ["*"] } 56 | }] 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /node_modules 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "10" 4 | - "node" 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Alexey Prokhorov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # twigjs-loader 2 | [](https://travis-ci.org/megahertz/twigjs-loader) 3 | [](https://badge.fury.io/js/twigjs-loader) 4 | [](https://david-dm.org/megahertz/twigjs-loader) 5 | 6 | ## Description 7 | 8 | twig.js loader for Webpack 9 | 10 | 11 | ## Installation 12 | 13 | This package requires node.js 8 at least. 14 | 15 | Install with [npm](https://npmjs.org/package/twigjs-loader): 16 | 17 | $ npm install -D twigjs-loader 18 | 19 | ## Usage 20 | 21 | ```js 22 | const indexView = require('./index.twig'); 23 | console.log(indexView({ variable1: 'value' })); 24 | ``` 25 | 26 | **webpack.config.js** 27 | 28 | ```js 29 | module.exports = { 30 | //... 31 | module: { 32 | rules: [ 33 | { 34 | test: /\.twig$/, 35 | use: 'twigjs-loader', 36 | }, 37 | //... 38 | ], 39 | }, 40 | //... 41 | } 42 | 43 | ``` 44 | 45 | ### With Express 46 | 47 | - [example](examples/express) 48 | - [typescript example](examples/typescript) 49 | 50 | `$ npm install twigjs-loader` 51 | 52 | **index.js:** 53 | ```js 54 | import * as express from 'express'; 55 | import { ExpressView } from 'twigjs-loader'; 56 | import indexView from './views/index.twig'; 57 | 58 | const app = express(); 59 | app.set('view', ExpressView); 60 | 61 | app.get('/', (req, res) => { 62 | res.render(indexView, { 63 | url: req.originalUrl, 64 | }) 65 | }); 66 | 67 | app.listen(8080); 68 | ``` 69 | 70 | ### On frontend 71 | 72 | - [example](examples/frontend) 73 | 74 | ```js 75 | import indexView from './views/index.twig'; 76 | 77 | document.body.innerHTML = indexView({ 78 | url: location.href, 79 | }) 80 | ``` 81 | 82 | ## Configure 83 | 84 | You can configure how a template is compiled by webpack using the 85 | `renderTemplate` option. For example: 86 | 87 | **webpack.config.js** 88 | 89 | ```js 90 | module.exports = { 91 | //... 92 | module: { 93 | rules: [ 94 | { 95 | test: /\.twig$/, 96 | use: { 97 | loader: 'twigjs-loader', 98 | options: { 99 | /** 100 | * @param {object} twigData Data passed to the Twig.twig function 101 | * @param {string} twigData.id Template id (relative path) 102 | * @param {object} twigData.tokens Parsed AST of a template 103 | * @param {string} dependencies Code which requires related templates 104 | * @param {boolean} isHot Is Hot Module Replacement enabled 105 | * @return {string} 106 | */ 107 | renderTemplate(twigData, dependencies, isHot) { 108 | return ` 109 | ${dependencies} 110 | var twig = require("twig").twig; 111 | var tpl = twig(${JSON.stringify(twigData)}); 112 | module.exports = function(context) { return tpl.render(context); }; 113 | `; 114 | }, 115 | }, 116 | }, 117 | }, 118 | //... 119 | ], 120 | }, 121 | //... 122 | } 123 | 124 | ``` 125 | 126 | ## Path resolving 127 | 128 | The module uses webpack for resolving template path, so it doesn't resolve 129 | path by itself. If you need custom file path resolution (eg namespaces), 130 | check [the example](examples/namespaces). 131 | 132 | ## Credits 133 | 134 | Based on [zimmo-be/twig-loader](https://github.com/zimmo-be/twig-loader) 135 | -------------------------------------------------------------------------------- /__specs__/index.spec.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { describe, expect, expectAsync, it } = require('humile'); 4 | const { compile, renderOutput } = require('./mock'); 5 | 6 | describe('twigjs_loader', () => { 7 | it('should load embed', async () => { 8 | const out = await compile('templates/embed-simple.twig'); 9 | expect(out).toContain('require("embed-base.twig");'); 10 | expect(out).toContain('require("embed-include.twig");'); 11 | expect(out).toContain('"value":"__specs__/templates/embed-base.twig"'); 12 | 13 | expect(renderOutput(out).trim()).toEqual([ 14 | 'START', 'A', 'new header', 'base footer', 'B', '', 'A', 'base header', 15 | 'base footer', 'extended', 'B', '', 'A', 'base header', 'extended', 16 | 'base footer', 'extended', 'B', '', 'A', 'Super cool new header', 17 | 'Cool footer', 'B', 'END', 18 | ].join('\n')); 19 | }); 20 | 21 | it('should extend the parent template', async () => { 22 | const out = await compile('templates/extender.twig'); 23 | expect(out).toContain('require("extendee.twig");'); 24 | expect(out).toContain('"value":"__specs__/templates/extendee.twig"'); 25 | 26 | expect(renderOutput(out).trim()).toBe('ok!'); 27 | }); 28 | 29 | it('should import macro', async () => { 30 | const out = await compile('templates/import.twig'); 31 | expect(out).toContain('require("macro.twig");'); 32 | expect(out).toContain('"value":"__specs__/templates/macro.twig"'); 33 | 34 | expect(renderOutput(out).trim()).toBe('Hello World'); 35 | }); 36 | 37 | it('should import selected macros from template', async () => { 38 | const out = await compile('templates/from.twig'); 39 | expect(out).toContain('require("macro-wrapped.twig");'); 40 | expect(out).toContain('"value":"__specs__/templates/macro-wrapped.twig"'); 41 | 42 | expect(renderOutput(out).trim()).toEqual([ 43 | 'Hello Twig.js', 44 | '
Sub: content
6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /__specs__/templates/extender.twig: -------------------------------------------------------------------------------- 1 | {% extends 'extendee.twig' %} 2 | 3 | {% block content %} 4 | {{ my.macro({}) }} 5 | {% endblock %} 6 | -------------------------------------------------------------------------------- /__specs__/templates/from.twig: -------------------------------------------------------------------------------- 1 | {% from "macro.twig" import echo %}{{ echo("Twig.js") }}{% from "macro-wrapped.twig" import wrapped_input as input, red_input %}{{ input('text') }}{{ red_input('password') }} 2 | -------------------------------------------------------------------------------- /__specs__/templates/import.twig: -------------------------------------------------------------------------------- 1 | {% import "macro.twig" as say %}{{ say.echo('World') }} 2 | -------------------------------------------------------------------------------- /__specs__/templates/include.twig: -------------------------------------------------------------------------------- 1 | Before{% include "test.twig" %}After -------------------------------------------------------------------------------- /__specs__/templates/macro-self.twig: -------------------------------------------------------------------------------- 1 | {% macro input(name, value, type, size) %}{% endmacro %} 2 | {% import _self as forms %}{{ forms.input('username') }}
3 | -------------------------------------------------------------------------------- /__specs__/templates/macro-wrapped.twig: -------------------------------------------------------------------------------- 1 | {% macro wrapped_input(name, value, type, size) %}{% import "macro-self.twig" as forms %}{{ forms.wrapped_input('username') }}
4 | -------------------------------------------------------------------------------- /__specs__/templates/macro.twig: -------------------------------------------------------------------------------- 1 | {% macro echo(name) %}Hello {{ name }}{% endmacro %} 2 | {% macro whitespace_echo( name ) %}Hello {{ name }}{% endmacro %} 3 | -------------------------------------------------------------------------------- /__specs__/templates/test.twig: -------------------------------------------------------------------------------- 1 | Test template = {{ test }} 2 | 3 | {% if flag %}Flag set!{% endif %} -------------------------------------------------------------------------------- /examples/express/.gitignore: -------------------------------------------------------------------------------- 1 | /dist 2 | /node_modules 3 | -------------------------------------------------------------------------------- /examples/express/.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /examples/express/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "twigjs-loader-example-express", 3 | "version": "1.0.0", 4 | "description": "twigjs-loader in express project", 5 | "private": true, 6 | "scripts": { 7 | "build": "webpack --mode=development", 8 | "start": "node dist/main.js" 9 | }, 10 | "devDependencies": { 11 | "webpack": "^4.41.2", 12 | "webpack-cli": "^3.3.9", 13 | "webpack-node-externals": "^1.7.2" 14 | }, 15 | "dependencies": { 16 | "express": "^4.17.1", 17 | "twig": "^1.13.3", 18 | "twigjs-loader": "1.x" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /examples/express/src/index.js: -------------------------------------------------------------------------------- 1 | import * as express from "express"; 2 | import { ExpressView } from "twigjs-loader"; 3 | import indexView from "./views/index.twig"; 4 | 5 | const app = express(); 6 | app.set("view", ExpressView); 7 | 8 | app.get("/", (req, res) => { 9 | res.render(indexView, { 10 | url: `${req.protocol}://${req.get("host")}${req.originalUrl}`, 11 | }) 12 | }); 13 | 14 | const port = process.env.NODE_PORT || 8080; 15 | app.listen(port, () => { 16 | console.log(`Example app listening on port ${port}.`); 17 | }); 18 | -------------------------------------------------------------------------------- /examples/express/src/views/index.twig: -------------------------------------------------------------------------------- 1 | {% extends './layout.twig' %} 2 | 3 | {% block content %} 4 |The current url is: {{ url }}
6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /examples/express/src/views/layout.twig: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |The current url is: {{ url }}
6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /examples/frontend/src/js/views/layout.twig: -------------------------------------------------------------------------------- 1 |The current url is: {{ url }}
6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /examples/namespaces/webpack.config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const nodeExternals = require('webpack-node-externals'); 5 | 6 | const LEGACY_REGEXP = /^(\w+)::/; 7 | 8 | /** 9 | * Transforms legacy namespace::template/path to @namespoace/template/path 10 | */ 11 | class LegacyNsResolverPlugin { 12 | apply(resolver) { 13 | const target = resolver.ensureHook('resolve'); 14 | resolver 15 | .getHook('resolve') 16 | .tapAsync('LegacyNsResolverPlugin', (request, resolveContext, callback) => { 17 | const requestPath = request.request; 18 | if (!requestPath.match(LEGACY_REGEXP)) { 19 | callback(); 20 | return; 21 | } 22 | 23 | const newRequest = { 24 | ...request, 25 | request: requestPath.replace(LEGACY_REGEXP, '@$1/'), 26 | }; 27 | 28 | resolver.doResolve(target, newRequest, null, resolveContext, callback); 29 | }); 30 | } 31 | } 32 | 33 | module.exports = { 34 | devtool: 'source-map', 35 | 36 | externals: [ 37 | nodeExternals(), 38 | ], 39 | 40 | module: { 41 | rules: [ 42 | { 43 | test: /\.twig$/, 44 | use: '../../index', 45 | }, 46 | ], 47 | }, 48 | 49 | resolve: { 50 | alias: { 51 | '@views': path.resolve(__dirname, 'src/views/include'), 52 | }, 53 | plugins: [new LegacyNsResolverPlugin()], 54 | }, 55 | }; 56 | -------------------------------------------------------------------------------- /examples/typescript/.gitignore: -------------------------------------------------------------------------------- 1 | /dist 2 | /node_modules 3 | -------------------------------------------------------------------------------- /examples/typescript/.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /examples/typescript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "twigjs-loader-example-typescript", 3 | "version": "1.0.0", 4 | "description": "twigjs-loader in typescript project", 5 | "private": true, 6 | "scripts": { 7 | "build": "webpack --mode=development", 8 | "start": "node dist/main.js" 9 | }, 10 | "devDependencies": { 11 | "@types/express": "^4.17.1", 12 | "@types/node": "^9.6.6", 13 | "awesome-typescript-loader": "^5.2.1", 14 | "typescript": "^3.7.0-dev.20191016", 15 | "webpack": "^4.41.2", 16 | "webpack-cli": "^3.3.9", 17 | "webpack-node-externals": "^1.7.2" 18 | }, 19 | "dependencies": { 20 | "express": "^4.17.1", 21 | "twig": "^1.13.3", 22 | "twigjs-loader": "1.x" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /examples/typescript/src/index.ts: -------------------------------------------------------------------------------- 1 | import * as express from "express"; 2 | import { Request, Response } from "express"; 3 | import { ExpressView } from "twigjs-loader"; 4 | import indexView from "./views/index.twig"; 5 | 6 | const app = express(); 7 | 8 | app.set("view", ExpressView); 9 | 10 | app.get("/", (req: Request, res: Response) => { 11 | res.render(indexView, { 12 | url: `${req.protocol}://${req.get("host")}${req.originalUrl}`, 13 | }) 14 | }); 15 | 16 | const port = process.env.NODE_PORT || 8080; 17 | app.listen(port, () => { 18 | console.log(`Example app listening on port ${port}.`); 19 | }); 20 | -------------------------------------------------------------------------------- /examples/typescript/src/views/index.twig: -------------------------------------------------------------------------------- 1 | {% extends './layout.twig' %} 2 | 3 | {% block content %} 4 |The current url is: {{ url }}
6 | {% endblock %} 7 | -------------------------------------------------------------------------------- /examples/typescript/src/views/layout.twig: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |