Coder Social home page Coder Social logo

gulp-swig's Introduction

Information

Packagegulp-swig
Description Compile Swig templates
Node Version โ‰ฅ 0.8
Swig Version 1.4.*

Build Status Dependencies

NPM

Learn more about gulp.js, the streaming build system

Learn more about templating with Swig

Donate

Install with NPM

$ npm install --save-dev gulp-swig

Usage

Compile to HTML

var swig = require('gulp-swig');

gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(swig())
    .pipe(gulp.dest('./dist/'))
});

Avoid caching when watching/compiling html templates with BrowserSync, etc.

.pipe(swig({defaults: { cache: false }}))

** NEW **

Inject data into your templates via the new gulp-data plugin. It creates a file.data property with the data you need. This new method makes it much easier and less restrictive for getting data, than the methods below it. I'd recommend using this new method.

/*
  Get data via JSON file, keyed on filename.
*/
var swig = require('gulp-swig');
var data = require('gulp-data');

var getJsonData = function(file) {
  return require('./examples/' + path.basename(file.path) + '.json');
};

gulp.task('json-test', function() {
  return gulp.src('./examples/test1.html')
    .pipe(data(getJsonData))
    .pipe(swig())
    .pipe(gulp.dest('build'));
});

** PRE version 0.7.0 (but still works) **

Inject variables from data object into templates

var swig = require('gulp-swig');
var opts = {
  data: {
    headline: "Welcome"
  }
};
gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(swig(opts))
    .pipe(gulp.dest('./dist/'))
});

Inject variables from JSON file into templates

If you've created a template called homepage.html you can create a JSON file called homepage.json to contain any variables you want injected into the template.

var swig = require('gulp-swig');
var opts = {
  load_json: true
};
gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(swig(opts))
    .pipe(gulp.dest('./dist/'))
});

Inject variables from both a data object and JSON file into templates

var swig = require('gulp-swig');
var opts = {
  load_json: true,
  data: {
    headline: "Welcome"
  }
};
gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(swig(opts))
    .pipe(gulp.dest('./dist/'))
});

By default, gulp-swig will look for the json data file in the same location as the template. If you have your data in a different location, there's an option for that:

var swig = require('gulp-swig');
var opts = {
  load_json: true,
  json_path: './data/',
  data: {
    headline: "Welcome"
  }
};
gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(swig(opts))
    .pipe(gulp.dest('./dist/'))
});

Inject variables using the Swig::setDefaults method, and set other swig defaults.

var swig = require('gulp-swig');
var opts = {
  defaults: { cache: false, locals: { site_name: "My Blog" } },
  data: {
    headline: "Welcome"
  }
};
gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(swig(opts))
    .pipe(gulp.dest('./dist/'))
});

Enable swig extensions using the setup option.

var swig = require('gulp-swig');
var marked = require('swig-marked');
var opts = {
  setup: function(swig) {
    marked.useTag(swig, 'markdown');
  }
};
gulp.task('templates', function() {
  gulp.src('./lib/*.html') // containing markdown tag: {% markdown %}**hello**{% endmarkdown %}
    .pipe(swig(opts))
    .pipe(gulp.dest('./dist/'))
});

LICENSE

(MIT License)

Copyright (c) 2013 Colyn Brown

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.

gulp-swig's People

Contributors

backflip avatar bordoni avatar clbrown avatar colynb avatar faergeek avatar iamjem avatar leo-fr8mate avatar yocontra avatar zce avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

gulp-swig's Issues

multiple varControls

I have a need to use multiple varControls for swig. In order to do so you have to use swig.Swig() to create isolated rendering environments.

Changing:
var tpl = swig.compile(String(file.contents), {filename: file.path});
to
var _swig = new swig.Swig(opts);
var tpl = _swig.compile(String(file.contents), {filename: file.path});

works but all the tests blow up and the setDefaults no longer works as expected. Not sure if this is a Swig or a gulp-swig issue...hoping you have a quick fix for this! Thanks!

Certain tags don't render

Hi,

Have a problem outputting the following tags html:-

  • svg
  • main

Swig removes the whole inline svg tag leaving only the content of the sub tag.

eg.

<svg xmlns="http://www.w3.org/2000/svg" width="76" height="76" viewBox="0 0 76 76">
   <title>Offer</title>
    <desc>Offer</desc>
    <path fill="#191919" d="M0 0h74.006c1.101 0 1.994.893 1.994 1.994v74.006l-76-76z"/>
    <text transform="matrix(.707 .707 -.707 .707 18.569 9.141)" 
        fill="#fff" font-family="'Arial-BoldMT'" 
        font-size="13">aanbieding
    </text>
</svg>

results in an out put of

Offer

Namespacing

Does this support namespaces? E.g. being able to set @App as an alias to a path:

{{ include('@App/Foo/bar.html.twig') }}

Especify block and template from gulpfile

Hello! Great plugin.

Sorry if this is a Noob question but my JS knowledge is limited.

I'm writing a documentation book in pure markdown that I want to publish in a website.

Is it possible to include all the content of pure markdown files in a swig block and extend always to the same template without problems of relative path?

Something like this (just a dumb example to help me to explain what I mean):

var swig = require('gulp-swig');

gulp.task('renderMarkdown', function() {
  gulp.src('./PATH/MD-FILES/**/*.md')
    .pipe(markdown())  // render markdown through marked
    .pipe(swig(
      defaults:{
        "block": "block-name",
        "template": "PATH/template.html"
    }))
    .pipe(gulp.dest('./dist/'))
});

Read data from a property on the file object?

I wanted to get your thoughts on this before submitting a pull request.

What do you think of adding an option to look up the data from a property on the file object that is passed in?

gulp.src('./*.swig')
    .pipe(addDataToFile())
    .pipe(swig({ property : 'nameOfDataAdded' }));

Other plugins such as lmtm/gulp-front-matter are attaching metadata to the file object, and it would be useful to be able to pass this to swig.

@contra, is this a good idea, or am I starting an anti-pattern here?

JSON variables into simple HTML file

I have a normal HTML file with a tag {{ name }} awaiting to be filled from an info.json file which looks like this:

  name: "Martin", 
  campaignName: "New campaign",
  copy: {
    headline: "Welcome",
    subheader: "This is the subheader"
  };

My gulp task looks like this which uses the data plugin

gulp.task('swig', function() {
  return gulp.src('./src/*.html')
    .pipe(data('./src/info.json'))
    .pipe(swig())
    .pipe(gulp.dest('./build'))
});

I may not even need the gulp-data plugin, but I was hoping it'd allow me to use a JSON object to populate some Swig tags in the HTML...is this the case?

Note: The gulp process errors on the first character in the JSON suggesting it wasn't expecting it...

Any help appreciated! Thanks.

Martin

support for base templates

Hello, I'd like to have a template structure (like below) where base.html is defined once and used everywhere. Apologies if this is not the right place for this question.

templates/
  base.html
  pages/
    vegetables.html 
    ...

Allow no accompanying json file

Whenever I create a template I must also make a blank json file to go with it or I just get an error that prevents compiling.

Hitting stack limit?

Hey :) This code snippet is causing something to hit the stack limit.

var swigSrc = 'templates/casestudy/*.html';
var swigDest = 'site/';

var swigOpts = {
  data: {
    asd: 'RAF WAS HERE'
  }
};

function swig() {
  gulp.src(swigSrc)
    .pipe(swig())
    .pipe(gulp.dest('./site/'));
}

gulp.task('deploy', deploy);
gulp.task('swig', swig);

and I'm getting the error

[18:00:49] Error: RangeError: Maximum call stack size exceeded
    at formatError (/Users/rafy/.nvm/v0.10.32/lib/node_modules/gulp/bin/gulp.js:161:10)
    at Gulp.<anonymous> (/Users/rafy/.nvm/v0.10.32/lib/node_modules/gulp/bin/gulp.js:187:15)
    at Gulp.emit (events.js:95:17)
    at Gulp.Orchestrator._emitTaskDone (/Users/rafy/Documents/rangle/rangle-website/node_modules/gulp/node_modules/orchestrator/index.js:264:8)
    at /Users/rafy/Documents/rangle/rangle-website/node_modules/gulp/node_modules/orchestrator/index.js:275:23
    at finish (/Users/rafy/Documents/rangle/rangle-website/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:21:8)
    at module.exports (/Users/rafy/Documents/rangle/rangle-website/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:36:10)
    at Gulp.Orchestrator._runTask (/Users/rafy/Documents/rangle/rangle-website/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/Users/rafy/Documents/rangle/rangle-website/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/Users/rafy/Documents/rangle/rangle-website/node_modules/gulp/node_modules/orchestrator/index.js:134:8)

Any ideas what might be wrong?

Compiling errors stops watcher even catching the error

Guys,

Even catching the errors, Gulp ins't able to keep executing after getting a Swig error.

Example:

[19:51:53] gulp-notify: [Error running Gulp] Error compiling template files: Unexpected end of tag "block" on line 92 in file /Users/[...].swig

...and the watcher stop working.

This is the Swig task:

module.exports = function (gulp, plugins, options) {
    gulp.task('templates', function() {
        return gulp.src('src/')
            .pipe(plugins.swig({
                defaults: {
                    cache: false
                },
                data: {
                    now: new Date()
                }
            }))
            .on('error', plugins.notify.onError('Error compiling template files: <%= error.message %>'))
            .pipe(gulp.dest('dist/'))
            .pipe(plugins.connect.reload())
            .pipe(plugins.notify({message: 'Templates tasks successfully completed!', onLast: true}));
    })
};

Watch stuck with first compile

I have a template that compiles fine when I first run the default task, but once it's running, watch is stuck, compiling the information that was in the first default run, regardless it changed or was deleted.

This is a basic gulpfile setup to reproduce the issue

var gulp        = require('gulp'),
    swig        = require('gulp-swig');

gulp.task('templates', function() {
  gulp.src('./dev/*.html')
    .pipe(swig())
    .pipe(gulp.dest('./build'))
});

gulp.task('watch', function() {
    gulp.watch('./dev/*.html', ['templates']);
});

gulp.task('default', ['templates', 'watch']);

Let's say I have this in ./dev/index.html:

{% set foo = "Bob" %}
<h1>Hello {{foo}}</h1>

I run gulp, it compiles to:

<h1>Hello Bob</h1>

Now, it's running watch. I change the data:

{% set foo = "Joe" %}
<h1>Hello {{foo}}</h1>

watch runs as expected, but it compiled to:

<h1>Hello Bob</h1>

Now I change the file completely,

{% set bar = "Larry" %}
<h1>Hello {{bar}}</h1>

I still get

<h1>Hello Bob</h1>

The file will only compile to <h1>Hello Larry</h1> when I stop watch and run gulp again. Then it will be stuck with compiling <h1>Hello Larry</h1>.

Common JSON data

Hi guys, I have an issue here, I can't actually add some global data that's common for all the templates. I've tried a solution offered on stackoverflow, but it didn't worked for me. I'm getting an error as it couldn't find the module 'src/data/global.json'.

This is my config object:

var swigConfig = {
    load_json: true,
    defaults:{
        cache: false
    },
    json_path: 'src/data/'
};

And this is my gulp task:

return  gulp.src('src/*.html').
        pipe(swig(swigConfig)).
        pipe(gulp.dest('build/'))

I would like to achieve something like this within my templates:

{{ global.someData }}

Thank you in advance

Use of extensions

What do you think about adding an init option? This would allow the use of extensions like swig-extras:

Example:

var swig = require('gulp-swig'),
    swigExtras = require('swig-extras');

gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(swig({
        init: function(swig) {
            swigExtras.useTag(swig, 'markdown');
        }
    }))
    .pipe(gulp.dest('./dist/'))
});

Or should this be done like this:

var swig = require('gulp-swig/node_modules/swig'),
    gulpSwig = require('gulp-swig'),
    swigExtras = require('swig-extras');

swigExtras.useTag(swig, 'markdown');

gulp.task('templates', function() {
  gulp.src('./lib/*.html')
    .pipe(gulpSwig())
    .pipe(gulp.dest('./dist/'))
});

Support Request: loop through array

Is there a way to loop through an array with this plugin?

EX:

{ "people": [
  { "name": "Pat Doe" },
  { "name": "John Doe" },
  { "name": "Jane Doe" }
]}

Given the above json, can it print each of the people in the people array?

add for json test condition

very good job !

You can test if exist json file:

diff -urN gulp-swig-master/index.js gulp-swig-master/index.js
--- gulp-swig-master/index.js 2014-02-04 04:16:00.000000000 +0200
+++ gulp-swig-master/index.js 2014-02-23 21:08:09.000000000 +0200
@@ -37,8 +37,12 @@

 if (opts.load_json === true) {
   var jsonPath = ext(file.path, '.json');
  •  var json = JSON.parse(fs.readFileSync(jsonPath));
    
  •  data = extend(json, data);
    
  •  fs.exists(jsonPath, function (exists) {
    
  •    if(exists){
    
  •      var json = JSON.parse(fs.readFileSync(jsonPath));
    
  •      data = extend(json, data);
    
  •    }
    
  •  });
    

    }

    var newFile = clone(file);

Cache false option not working

Hi,

I am having issues with caching on gulp watch. This is how I have it set:

var swigOptions = {
  load_json: true,
  json_path: './data',
  defaults: { cache: false },
  data: JSON.parse(fs.readFileSync('./data/data.json')),
  setup: function(swig) {
    swig.setDefaults({
      loader: swig.loaders.fs(__dirname + '/templates' ),
      cache: false
    });
  }
};

//Template task
gulp.task('templates:site', function() {
  gulp.src([
    paths.src.templates + '/index.html',
    paths.src.pages.site + '/*.html',
    paths.src.pages.site + '/**/*.html'
  ])
  .pipe(plumber())
  .pipe(swig(swigOptions))
  .pipe(gulp.dest(paths.frontend.root))
  .on("end", reload);
});

// I have other tasks for compiling templates in other places of the project
gulp.task('templates', ['templates:site', 'templates:bdg', 'templates:sg']);

// this is how the watch task is set
gulp.task('watch', function() {
  //... some other tasks
  gulp.watch(paths.src.data + '/**/*.json', ['templates']);
  gulp.watch(paths.src.templates + '/**/*.html', ['templates']);
});

Everything works when I run gulp or the templates tasks by itself, I get the update version of my json files, but not on watch.

You can see that I try to set cache to false in different alway, but with no luck.

I was using version 0.7.4, have updated to version 0.8 but nome of them seem to work with the cache set to false.

Thanks for looking into it ;)

Specify json template paths

My swig templates reside in templates. I'd love to have the associated template JSON data reside in a data folder as opposed to keeping everything in the same folder. Possibrew?

clone(options) breaks ability to pass data around.

The way the code is now it breaks when you need to run a function from the html that is defined in the context. The way it is now, variables are static once they are passed into swig and they are unable to be modified.

var opts = options ? clone(options) : {};

should be

var opts = options ? options : {};

possible to use (angularjs) ng-repeat in templates?

I am attempting to build an html pattern library which will be used by AngularJS to build templates. The templates should be able to use default data (supplied in the file via Yaml Front-Matter) to build the templates.

Is it possible to use ng-repeat in my templates when gulp converts the data via gulp-data and sends it into gulp-swig?

example

github repo: gulp-swig-ng-repeat

gulpfile.js

'use strict';
var gulp = require('gulp');
var frontMatter = require('front-matter');
var swig = require('gulp-swig');
var data = require('gulp-data');

/*
  Get data via front matter
*/
gulp.task('fm-test', function() {
  return gulp.src('./patterns/**/*.html')
    .pipe(data(function(file) {
      var content = frontMatter(String(file.contents));
      file.contents = new Buffer(content.body);
      console.log(content.attributes)
      return content.attributes;
    }))
    .pipe(swig())
    .pipe(gulp.dest('build'));
});

ng-repeat html template


---
something: thing
levelOneNavObject:
  mainItemOne:
    title: main item one
    url: google.com
  mainItemTwo:
    title: main item two
    url: yahoo.com
    levelTwoNavObject:
      subItemOne:
        title: sub item one
        url: yahoo.com/1
      subItemTwo:
        title: sub item two
        url: yahoo.com/2
      subItemThree:
        title: sub item three
        url: yahoo.com/3
  mainItemThree:
    title: main item three
    url: bing.com

---
<p>{{something}}</p>
<p>{{levelOneNavObject.mainItemOne.title}}</p>
<nav class="navigation--MAIN">
  <ul class="navigation--primary">
    <li class="navigation--primary-list-item" ng-repeat="mains in levelOneNavObject"><a href="http://{{mains.url}}">{{mains.title}}</a></li>
  </ul>

</nav>

thanks for any help,
Scott

Need a new version with removal of gulp-util

Hello C Brown,

Can you please help me know, when will be the new gulp-swig version available. You last released version is using gulp-util which now deprecated. I can see that you have updated the source. Just looking for the new version. I using gulp-swig in one of my application.

Thanks
Sandeep

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.