Take a swig of the best template engine for JavaScript.

Overview

NOT MAINTAINED

Fork and use at your own risk.

Swig Build Status Dependency Status NPM version NPM Downloads

Swig is an awesome, Django/Jinja-like template engine for node.js.

Features

  • Available for node.js and major web browsers!
  • Express compatible.
  • Object-Oriented template inheritance.
  • Apply filters and transformations to output in your templates.
  • Automatically escapes all output for safe HTML rendering.
  • Lots of iteration and conditionals supported.
  • Robust without the bloat.
  • Extendable and customizable. See Swig-Extras for some examples.
  • Great code coverage.

Need Help? Have Questions? Comments?

Installation

npm install swig

Documentation

All documentation can be viewed online on the Swig Website.

Basic Example

Template code

<h1>{{ pagename|title }}</h1>
<ul>
{% for author in authors %}
    <li{% if loop.first %} class="first"{% endif %}>{{ author }}</li>
{% endfor %}
</ul>

node.js code

var swig  = require('swig');
var template = swig.compileFile('/absolute/path/to/template.html');
var output = template({
    pagename: 'awesome people',
    authors: ['Paul', 'Jim', 'Jane']
});

Output

<h1>Awesome People</h1>
<ul>
    <li class="first">Paul</li>
    <li>Jim</li>
    <li>Jane</li>
</ul>

For working example see examples/basic

How it works

Swig reads template files and translates them into cached javascript functions. When we later render a template we call the evaluated function, passing a context object as an argument.

License

Copyright (c) 2010-2013 Paul Armstrong

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Template variables can now execute functions and methods

    Template variables can now execute functions and methods

    Before:

    <p>Hi, this is {{ user.fullName() }}</p>
    

    Would return nothing, even though fullName() is a real function. This PR fixes it.

    Function call executes in the scope of the variable, which means that in this example, if fullName() usesthis, it refers to user.

    Refs #174, #151, #145, #140, #100, #90, #89

    opened by fzaninotto 23
  • Add a precompile/registerTemplate feature for server-side processing

    Add a precompile/registerTemplate feature for server-side processing

    Hi!

    Thanks for Swig, I enjoy using it much more than Handlebars. One feature that Handlebars has that was sorely missed is the ability to generate the parsed templates on the server-side and deliver them to the client (or build them as part of a process and bundle compiled templates). The only reason for this is performance, and it's very noticeable on mobile/phonegap implementations.

    I've added this feature, with a unit test and docs. It was pretty easy to get everything working, however the only thing that I wasn't entirely happy with is keeping a reference to the generated code in the resulting template object. I don't think this is going to be a big deal, but we can think of some other and more efficient way for that if you'd like!

    Thanks and Happy Holidays!

    -Jay

    opened by jshirley 13
  • Allow multiple configs & separate caches in single runtime

    Allow multiple configs & separate caches in single runtime

    This pull request allows several instances of the Swig engine to be used in the same runtime. It does this by passing around an optional config paramater to take the place of the private, but globally defined _config container. By defining _config at the module level, it was impossible to change configuration options between two different use cases in the same run time.

    All public API functions work the same as they always have. If the optional config parameter is not passed to them, then the _config global will be used instead. The new exports.engine() constructor function can be called multiple times in the same runtime to create different instances of the Swig API with different configurations.

    opened by kixxauth 11
  • Extract file system based functions into template loaders

    Extract file system based functions into template loaders

    I hit the same issue as #370 when I tried to use swig in browser. Precompiling templates is not useful in some cases and does not work with latest code. That is why I tryed to fix it and and add some flexibility.

    Loaders provides interface for extending swig for using different template sources. By default FileSystemLoader will be used and it acts as current swig implementation. As an example I added MemoryLoader which might be used in browser. It loads templates from predefined hash object.

    I know that my pull request needs to be updated with more documentation and tests, but I want to know you opinion about it before.

    Thank you

    opened by MaratFM 9
  • Add detailed error messages.

    Add detailed error messages.

    I like SWIG very much but it was difficult to find out what was wrong with my first template attempts. I added a bubbling error message where every part in the error catching chain adds its details. I hope you will find the proposed changes useful.

    opened by thomaswhite 8
  • Don't auto-escape any function output

    Don't auto-escape any function output

    Discussed here: https://groups.google.com/forum/#!topic/swig-templates/tJG7dgxPOq8

    Basically, the general consensus is that if you're sending a function to the template engine to be run and provide output, that your application will properly escape the output and Swig does not need to do so on its own. This will also fix a myriad of issues with macros, forcing them to never auto-escape.

    Fixes gh-306 Fixes gh-302 Fixes gh-297

    opened by paularmstrong 7
  • Added support for optional raw arguments

    Added support for optional raw arguments

    This pull request does not break any use case with the raw tag instead it will parse a given argument when given as boolean and enable raw depending on that argument.

    For example:

    {% spaceless %}
    <section>
    {% raw %}<p>I like these brackets {{ }} yeah</p>{% endraw %}
    {% raw client %}
    <h3>{{ name }}</h3>
    <!-- can be used by client -->
    {% endraw %}
    </section>
    {% include './somefile.html' %}
    {% endspaceless %}
    

    This allows to have "server-prepared" templates compiled by browserify, component.io transforms. So you would not have to handle includes and spaceless on the client side.

    Please review if everything is okay so far. Also you may have an idea how to remove code duplication on parser implementation of raw (is copied from the if tag).

    opened by bodokaiser 6
  • Contextual support for object method calls

    Contextual support for object method calls

    A common use-case for functions is to call them in a particular context. The current master branch applies all method calls in the global scope, which is problematic for OO applications.

    Pseudo-code

    If token.type == _t.PARENOPEN and prevToken.type == _t.VAR
        Assume method call, and bind to method's object scope, with a trailing comma
    If token.type == _t.PARENCLOSE and previous token was a method call
        Strip trailing comma from output buffer
    

    Additionally, I refactored the checkDot and buildDot methods, and borrowed them for this purpose. Relevant test case added and passes.

    opened by landons 6
  • Express 3 support

    Express 3 support

    I write a __express function for express 3. but I think that consolidate is a better choice in express 3 alpha https://github.com/visionmedia/consolidate.js

    opened by baryon 6
  • Adds support for CSP-strict environments like node-webkit and atom-shell

    Adds support for CSP-strict environments like node-webkit and atom-shell

    I'm writing a rather complicated package for the Atom editor and I require templating functionality. In order to avoid running my server/templating in a node subprocess, I've added a safeMode flag to swig which prompts swig to use loophole to run the compilation in a vm context. This allows my Atom package to be installed/run normally. Without this functionality swig cannot be used as a dependency in environments like node-webkit or atom-shell that have (rightfully so) strict content security policies.

    Thanks in advance for your consideration.

    -Joe

    opened by joeferraro 5
  • Null should yield empty string when resolving variable

    Null should yield empty string when resolving variable

    This is related to #236. Am upvoting for showing empty string when resolving null object.

    This is more similar to engines that swig is based on (Jinja/Django both resolves None as empty strings) and most of the time is more desired (I guess) than opaque [Object object].

    While writing tests was pretty straightforward, have to admit I am not sure about the implementation.

    Let me know what you think.

    opened by lukaszb 5
Releases(v1.4.2)
  • v1.4.2(Aug 4, 2014)

    • Added Report JS parse errors with template filenames. gh-492
    • Fixed Ensure block-level tags (set, etc) are parsed in correct order. gh-495
    • Fixed Ensure import tag uses current Swig instance's loader. gh-421, gh-503
    • Fixed Allow disabling cache on compile/render functions directly. gh-423
    • Fixed Ensure compilation does not leak global variables. gh-496
    • Fixed Fix for-loops to run on strings. gh-478, gh-479
    • Fixed Allow macro output to be assigned using set tag. gh-499, gh-502
    Source code(tar.gz)
    Source code(zip)
    swig.js(140.60 KB)
    swig.js.map(61.84 KB)
    swig.min.js(45.39 KB)
  • v1.4.1(Jul 3, 2014)

  • v1.4.0(Jul 3, 2014)

    • Changed Allow variable tokens to start with $. gh-455
    • Changed fs loader should take cwd as default base path. gh-419
    • Changed handle errors which occur at the time of rendering. gh-417
    • Changed default options in bin (varControls, tagControls, cmtControls). gh-415
    • Changed null should yield empty string when resolving variable. gh-408
    • Added Escape character for date filter argument. gh-427, gh-432
    • Added Make if and elseif throw a better error message when a tag body is omitted. gh-425
    • Fixed don't throw errors on accessing property of null object. gh-471
    • Fixed loop variables work correctly in nested loops. gh-433
    • Fixed Some IE8 compatibility (require es5). gh-428
    Source code(tar.gz)
    Source code(zip)
    swig.js(139.66 KB)
    swig.js.map(61.56 KB)
    swig.min.js(44.97 KB)
  • v1.3.2(Jan 28, 2014)

  • v1.3.0(Jan 20, 2014)

    • Changed Removed official node v0.8.x support
    • Added Custom template loader support. gh-377, gh-384, gh-382
    • Added Ability to set root path using template loaders. gh-382, gh-293
    • Added CLI now accepts custom filter and tag arguments. gh-391
    • Added Allow set tag to set keys on objects with bracket and dot-notation. gh-388
    • Added groupBy filter from swig-extras. gh-383
    • Fixed swig.run filepath arg is always optional. gh-402
    • Fixed Filters on non-empty functions apply correctly. gh-397
    • Fixed Filters applied to functions w/ & w/o dotkeys. gh-365
    • Fixed date filter N option returns correct number. gh-375
    • Fixed Ensure getting parent template checks cache if on. gh-378
    Source code(tar.gz)
    Source code(zip)
    swig.js(117.09 KB)
    swig.js.map(49.27 KB)
    swig.min.js(36.28 KB)
  • v1.2.2(Dec 3, 2013)

  • v1.2.1(Dec 3, 2013)

  • v1.2.0(Dec 2, 2013)

    • Added Filepath parameter can be passed to swig.run to allow extends in-browser. gh-349
    • Changed Use local-context first for var lookups. gh-344, gh-347
    • Changed Allow DOTKEY after functions/objects/filters. gh-355
    • Changed Context of for-tags carries into includes. gh-356
    • Changed When a callback is passed into compileFile, catch all errors thrown by compile and pass the error to callback. gh-340
    • Fixed Instances of Swig retain their options properly. gh-351
    • Fixed Fix misc documentation issues. gh-359, gh-358
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Oct 2, 2013)

    • Added Allow logic in default parsing. gh-326
    • Fixed Error when attempting to wrap spaceless tag around macro/function output. gh-336
    • Fixed Don't overwrite keys on the locals object. gh-337
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Sep 23, 2013)

  • v1.0.0-rc3(Sep 14, 2013)

    • Fixed Allow bools in token parser by default. gh-321
    • Fixed Allow variables as object values. gh-323
    • Fixed Don't partially match logic words. gh-322
    • Fixed Parent tag in parent's block with no local block edge case. gh-316
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-rc2(Sep 6, 2013)

    • Changed Function output from variable blocks are no longer auto-escaped. gh-309
    • Fixed Allow nested macros to work when importing. gh-310
    • Fixed swig.setDefaultTZOffset. gh-311
    • Changed set tag assigns to the local context, allowing setting within for loops, etc. gh-303
    • Fixed Standardize variable undefined checking. gh-301
    • Fixed Remove multiple redefinition of block-level tags in compiled templates.
    • Fixed Performance issue with compile if no default locals are defined.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-rc1(Aug 28, 2013)

    • Added include tag now accepts only (and is preferred, if possible). gh-240
    • Added swig.version and -v to cli
    • Changed Deprecated raw filter. Use safe.
    • Changed Allow import and macro tags to be outside of blocks. gh-299
    • Changed Don't escape macro output. gh-297
    • Changed (Custom) Filters can be marked as safe to disable auto-escaping. gh-294
    • Fixed {% for k,v ... %} tag syntax assigned variables backwards.
    • Fixed Filters being applied to empty functions throwing errors. gh-296
    • Fixed include paths on windows. gh-295
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-pre3(Aug 21, 2013)

  • v1.0.0-pre2(Aug 18, 2013)

    • Changed Binary: Allow --method-name to be a shortcut for --wrap-start var setting.
    • Changed Make reverse filter an alias for sort(true).
    • Added Allow asyncronous compileFile and renderFile operations. gh-283
    • Added Filter: sort.
    • Added Allow {% end[tag] tokens... %}. gh-278
    • Added Built source map for minified browser source.
    • Added Contextual support for object method calls. gh-275
    • Added parser.on('start'|'end'... options. gh-274
    • Added Allow object prototypal inheritance. gh-273
    • Fixed Prevent circular extends. gh-282
    • Fixed Throw an error if reserved word is used as var. gh-276
    • Fixed Add filename to errors if possible. gh-280
    • Fixed Filters work over arrays/objects if possible. gh-259
    • Fixed Allow {% parent %} to work in middle parent templates. gh-277
    • Fixed Allow newlines in tags/vars/comments. gh-272
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-pre1(Aug 16, 2013)

    This is a completely rewritten version of Swig that includes many enhancements and additional benefits. Much throughout the API and usage has changed. For more information read the migration guide

    • Changed Completely rewritting parsing engine supports many more syntaxes and is much easier to extend.
    • Changed There is no more swig.init method.
    • Changed Custom filters can be added using swig.addFilter
    • Changed Custom tags can be added using swig.addTag
    • Changed Writing custom tags uses an entirely new, simplified format
    • Changed Removed the underscore/lodash dependency
    • Changed Template parsing has been completely rewritten
    • Changed swig.compileFile returns a function that renders templates, not an object
    • Changed Express-compatible using swig.renderFile.
    • Changed extends, import, and include now reference files with relative paths from the current file (info).
    • Changed extends may no longer accept variables (info).
    • Changed else if tag is now elseif or elif.
    • Changed Removed only argument from include.
    • Changed allow _, $ to start var names in templates.
    • Changed Documentation is auto-generated from jsdoc comments in-files.
    • Added Ability to set custom var/tag/comment controls ({{, }}, etc, can be customized).
    • Added Variable/string concatenation gh-135.
    • Added Binary application for compile, run, and render (Lets you pre-compile templates into JS functions for client-side delivery).
    • Fixed Lots.
    Source code(tar.gz)
    Source code(zip)
  • v0.14.0(Sep 3, 2013)

  • v0.13.5(Sep 3, 2013)

  • v0.13.4(Sep 3, 2013)

  • v0.13.3(Sep 3, 2013)

  • v0.13.2(Sep 3, 2013)

  • v0.13.1(Sep 3, 2013)

  • v0.13.0(Sep 3, 2013)

  • v0.12.1(Sep 3, 2013)

    • Added More information on some parser errors
    • Added indent parameter to json_encode filter to support pretty-printing.
    • Added support for variables as extends tag parameters
    • Fixed Compile errors in Android and other random browsers
    • Fixed Misc documentation
    • Fixed Leaking __keys variable into global scope
    Source code(tar.gz)
    Source code(zip)
  • v0.12.0(Sep 3, 2013)

  • v0.11.2(Sep 3, 2013)

  • v0.11.1(Sep 3, 2013)

  • v0.11.0(Sep 3, 2013)

    • Added Support for Windows style paths gh-57
    • Added ignore missing tokens to include tag
    • Changed include tag with context to only work if context is an object
    • Changed autoescape tag controls no longer 'yes' or 'no'. Use true and false
    • Changed parser is now passed into tags as an argument
    • Changed don't require passing context object when rendering template
    • Fixed dateformats N and w gh-59
    • Fixed number changing to string after add filter or set from variable gh-53 gh-58
    • Fixed speed decrease caused by loop.cycle fixed
    • Fixed Ensure set tag bubbles through extends and blocks
    Source code(tar.gz)
    Source code(zip)
  • v0.10.0(Sep 3, 2013)

    • Added loop.index0, loop.revindex, loop.revindex0, and loop.cycle gh-48
    • Added init config extensions for 3rd party extension access in custom tags gh-44
    • Added Whitespace Control gh-46
    • Changed The empty tag in for loops is now else gh-49
    • Changed forloop vars to loop closes gh-47
    • Fixed include tag's with and only args documentation gh-50
    Source code(tar.gz)
    Source code(zip)
  • v0.9.4(Sep 3, 2013)

    • Fixed parent tag would not render when called within tags gh-41
    • Fixed Documentation for forloop.index & forloop.key gh-42
    • Fixed Errors when using include inside base template block tags gh-43
    • Fixed Allow set tag to set values to numbers gh-45
    • Fixed set tag for booleans using too many checks
    Source code(tar.gz)
    Source code(zip)
Owner
Paul Armstrong
Paul Armstrong
Variation-template - Variation is a PSD template that is covered into a web template using HTML5, CSS3, Bootstrapv4.6, JavaScript.

Variation Template Design Variation is a PSD website template. In this project this template is designed with HTML. Deployment This site is deployed a

Bipronath Saha 1 Jan 1, 2022
The fastest + concise javascript template engine for nodejs and browsers. Partials, custom delimiters and more.

doT Created in search of the fastest and concise JavaScript templating function with emphasis on performance under V8 and nodejs. It shows great perfo

Laura Doktorova 4.9k Dec 31, 2022
A K6 Multi Scenario template applying some best practices along some examples

K6-Multi-Scenario-Template It is a performance testing template that shows how to use K6 to implement a Multi Scenario template applying some best pra

Swiss Life OSS 33 Nov 27, 2022
Pug – robust, elegant, feature rich template engine for Node.js

Pug Full documentation is at pugjs.org Pug is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.j

Pug 21.1k Dec 30, 2022
eXtensible Template Engine lib for node and the browser

xtemplate High Speed, eXtensible Template Engine lib on browser and nodejs. support async control, inheritance, include, logic expression, custom func

xtemplate 553 Nov 21, 2022
Embedded JS template engine for Node, Deno, and the browser. Lighweight, fast, and pluggable. Written in TypeScript

eta (η) Documentation - Chat - RunKit Demo - Playground Summary Eta is a lightweight and blazing fast embedded JS templating engine that works inside

Eta 682 Dec 29, 2022
1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.

JavaScript Templates Contents Demo Description Usage Client-side Server-side Requirements API tmpl() function Templates cache Output encoding Local he

Sebastian Tschan 1.7k Jan 3, 2023
A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)

Nunjucks Nunjucks is a full featured templating engine for javascript. It is heavily inspired by jinja2. View the docs here. Installation npm install

Mozilla 8k Dec 30, 2022
Highly opinionated project template for Serverless Framework that follows and applies hexagonal architecture principle to serverless world. Prepared with easy testing in mind.

serverless-hexagonal-template Highly opinionated project template for Serverless Framework that applies hexagonal architecture principles to the serve

Paweł Zubkiewicz 126 Dec 26, 2022
Script Template Fivem in Type Script

fivem-ts ?? A Typescript Template for FiveM ?? This is a basic template for creating a FiveM resource using Typescript. It includes webpack config fil

Vinícius Pereira 3 Jun 11, 2021
Tailwind & Next Mentorship Template

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Nauval 21 May 22, 2022
Examples of how to re-create the WordPress Template Hierarchy using headless clients and WPGraphQL

WPGraphQL Template Hierarchy Debugger This is a project to demonstrate how to re-create the WordPress template hierarchy with Headless WordPress using

Jason Bahl 17 Oct 29, 2022
Template to create reactjs component library which will help you to create your dream library.

reactjs-library-template Template to create reactjs component library which will help you to create your dream library. How to use Commands to setup e

Nishant Tomar 1 Dec 25, 2021
A template to be used for creating js/scss projects and deploy them to github pages

A template to be used for creating js/scss projects and deploy them to github pages

Cariera în IT 15 Oct 30, 2022
Low tech template for a reduced carbon impact :seedling:

Enverse minimalist front-end template ?? ?? For all else, use Astro.build ?? Recomended package manager: pnpm Preact + Typescript + Vite How to use: F

null 2 Jan 10, 2022
Obsidian To HTML, A template for building obsidian style notes to a static site

oth (Obsidian To HTML) This is a template for publishing obsidian notes as a static site. The goal of the project is to stay minimal, since this is a

Ulisse mini 11 Nov 4, 2022
My discord.js bot template

My discord.js Bot Template This repository is an ongoing project to extract core pieces of the discord.js bots and ecosystems I run into a reusable te

Ian Mitchell 8 Mar 3, 2022
Minimal templating with {{mustaches}} in JavaScript

mustache.js - Logic-less {{mustache}} templates with JavaScript What could be more logical awesome than no logic at all? mustache.js is a zero-depende

Jan Lehnardt 15.7k Jan 7, 2023
Asynchronous Javascript templating for the browser and server

Dust.js Asynchronous Javascript templating for the browser and server. This fork is maintained by LinkedIn. Install NPM Important: We recommend that y

LinkedIn 2.9k Dec 31, 2022