📜 ⬆️ ⬇️

Swig - JavaScript Template Engine with Django Template Syntax

I noticed that no one wrote on Habré about the excellent JavaScript template engine Swig .

JavaScript is becoming more and more popular in the past and is finding new and unexpected applications. So this trend didn’t get me around, so with just-for-fun developing one project I couldn’t resist and decided to try using JS simultaneously on the server (Node.JS), the web client (Backbone.js - everything is serious :)) and in the mobile application (PhoneGap). The next step for me was the choice of the template engine, and the support of both the node and the browser was a mandatory criterion. Before that, I dealt mainly with Django Template Language, so the choice fell on Swig.

Swig Features:

Node quickstart

Installation
npm install swig 

Creating a template
 <h1>{{ pagename|title }}</h1> <ul> {% for author in authors %} <li{% if loop.first%} class="first"{% endif %}> {{ author }} </li> {% else %} <li>There are no authors.</li> {% endfor %} </ul> 

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

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

In the browser

Using Swig in a browser is not fundamentally different from using a node, except for two things:

We connect
 <script type='text/javascript" src="//path/to/swig/swig.js"> 

Preparing a template
 var template = swig.compile('<p>{% block content %}{% endblock %}</p>', { filename: 'main' }); var mypage = swig.compile('{% extends "main" %}{% block content %}Oh hey there!{% endblock %}', { filename: 'mypage' }); 

Render
 console.log(mypage.render({})); 

And we get
 <p>Oh hey there!</p> 

Project page
Documentation
Project on Github

')

Source: https://habr.com/ru/post/174207/


All Articles