Coder Social home page Coder Social logo

gulp-ejs's Introduction

gulp-ejs NPM version Build Status Dependency Status

ejs plugin for gulp

Usage

First, install gulp-ejs as a development dependency:

npm install --save-dev gulp-ejs

Then, add it to your gulpfile.js:

var ejs = require("gulp-ejs")

gulp.src("./templates/*.ejs")
	.pipe(ejs({
		msg: "Hello Gulp!"
	}))
	.pipe(gulp.dest("./dist"))

Watch mode error handling (for gulp v3 or below)

If you want to use gulp-ejs in a watch/livereload task, you may want to avoid gulp exiting on error when, for instance, a partial file is ENOENT or an ejs syntax error.

Here's an example on how to make it work:

var ejs = require('gulp-ejs')
var log = require('fancy-log')

gulp.src('./templates/*.ejs')
	.pipe(ejs({
		msg: 'Hello Gulp!'
	}).on('error', log))
	.pipe(gulp.dest('./dist'))

This will make gulp log the error and continue normal execution.

Please note that you don't need to do this for Gulp v4.

Accessing the ejs object

The ejs object is also exported and you can use it to configure ejs:

const ejs = require('gulp-ejs')

ejs.__EJS__.fileLoader = function () { /* custom file loader */ }

Note: As of version 4, the exported ejs object was renamed from ejs to __EJS__.

Async rendering (requires runtime support)

Since ejs v2.5.8 added support for promise/async-await renderFile, you can now use this option with gulp-ejs v4.1.0.

You can use async/await in your ejs templates by passing { async: true } in the ejs options hash:

const ejs = require('gulp-ejs')

async function foobar() { /* async task */ }

gulp.src('./templates/*.ejs')
	.pipe(ejs({ foobar }, { async: true }))
	.pipe(gulp.dest('./dist'))

Then in your templates use await to call async functions. Here's an example:

<%= await foobar() %>

API

ejs(data, options)

data

Type: hash Default: {}

A hash object where each key corresponds to a variable in your template.

Note: As of v1.2.0, file.data is supported as a way of passing data into ejs. See this. If both file.data and data are passed, they are merged (data works as default for ejs options and file.data overrides it.)

options

Type: hash Default: {}

A hash object for ejs options.

For more info on ejs options, check the project's documentation.

Renaming file extensions

As of version 4, the third api parameter settings was removed. You can no longer provide an extension. This is because it falls out of the scope of gulp-ejs. So if you need to save the file with a different extension you can use gulp-rename.

Here's an example for template files with .ejs extension that are rendered into .html files:

const ejs = require('gulp-ejs')
const rename = require('gulp-rename')

gulp.src('./templates/*.ejs')
  .pipe(ejs({ title: 'gulp-ejs' }))
  .pipe(rename({ extname: '.html' }))
  .pipe(gulp.dest('./dist'))

License

MIT License

gulp-ejs's People

Contributors

abrkn avatar broud avatar dependabot-preview[bot] avatar elct9620 avatar greenkeeper[bot] avatar greenkeeperio-bot avatar iktakahiro avatar jtomaszewski avatar kilianc avatar kt3k avatar mrdinckleman avatar pdehaan avatar rogeriopvl avatar thedancingcode avatar tietew avatar tomchentw 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

gulp-ejs's Issues

comments in ejs?

Hi,
putting this in ejs: <%# Comment %>
and got :

stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
[gulp] Error in plugin 'gulp-ejs': SyntaxError: Unexpected token ILLEGAL in "

Any updates?

Filename option not working

Hi,

The filename option is not working after the compilation and output process.

// ...
import gulpEjs from 'gulp-ejs';

const paths = {
    // ...
    'ejs'    : {
              'main': 'www/ejs/main.ejs',
              'dest': {
                  'path'          : 'www',
                  // @todo option not workin
                  'fileName'      : 'index',
                  'fileExtenstion': '.html'
              }
          }
}

// ...

/* --------------------------------------------------------------------------
 * EJS
 * --------------------------------------------------------------------------
 */

/**
 * Compile the main EJS file located in `paths.ejs.main` and output the result to
 * `paths.ejs.dest.path`/`paths.ejs.dest.fileName`.`paths.ejs.dest.fileExtenstion`
 *
 * @returns {*|Stream} Gulp callback
 */
export function ejs () {
    return gulp.src(paths.ejs.main)
               .pipe(gulpEjs({}, {"filename": paths.ejs.dest.fileName}, {"ext": paths.ejs.dest.fileExtenstion}))
               .pipe(gulp.dest(paths.ejs.dest.path));
}

gulp es output a www/main.html instead of www/index.html, it takes the name of the main file and doesn't change it.

rom1@GT72VR-7RE:~/facebook-cordova$ gulp --version
[02:12:16] Requiring external module babel-register
[02:12:16] CLI version 1.3.0
[02:12:16] Local version 4.0.0-alpha.2

Thanks ;p

Watcher freezing on error

Hi. The problem I faced is that when an error occurs the error message is displayed in console and then the watcher/livereload stops further work. So if you then correct the error nothing will happen (although the watcher task in console is still running everything is stuck just showing the last error message).

Here is the code:

const connect = require('gulp-connect')
...
gulp.task('ejs', () => {
	...
	return gulp.src('src/templates/*.ejs')
		.pipe(ejs({...}, {...}).on('error', gutil.log))
		.pipe(gulp.dest('./dist'))
		.pipe(connect.reload())
})

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

Working with `gulp-data`

Hello!

I tried several times use gulp-data with gulp-ejs, but without success.
Here are my attempts:

  • 1
gulp.task("views", function() {
  return gulp.src(Object.values(paths.sources.views))
    .pipe(g.plumber({
      errorHandler: alert
    }))
    .pipe(g.ejs(g.data(function(file){
      return JSON.parse(n.fs.readFileSync('./models/' + n.path.basename(file.path) + '.json'));
    }), {
      cache: true,
      compileDebug: stage < 0,
      client: true,
      ext: '.html'
    }).on("error", g.util.log))
    .pipe(g.if(stage > 0, g.htmlmin()))
    .pipe(gulp.dest(getPath()))
    .pipe(bs.stream());
});
  • 2
gulp.task("views", function() {
  return gulp.src(Object.values(paths.sources.views))
    .pipe(g.plumber({
      errorHandler: alert
    }))
    .pipe(g.data(function(file){
      return JSON.parse(n.fs.readFileSync('./models/' + n.path.basename(file.path) + '.json'));
    }))
    .pipe(g.ejs({}, {
      cache: true,
      compileDebug: stage < 0,
      client: true,
      ext: '.html'
    }).on("error", g.util.log))
    .pipe(g.if(stage > 0, g.htmlmin()))
    .pipe(gulp.dest(getPath()))
    .pipe(bs.stream());
});

Here is a portion of my template:

<% projects.forEach(function(project){ %>
                    <%- include('../molecules/project', {project: project}); %>
                <% }); %>

And here is a portion of my json:

{
        "projects": {
            "earthdiscover": {
                "name": "Earth Discover", ....

What is the solution?
Thanks.

Making pages based on layout

If I want to make pages, based on layout like this:

<!DOCTYPE html>
<html lang="en">
<%- include('../_widgets/head'); -%>
<body>
       <div class="view-wrapper index">
	   <%- include('../_widgets/header'); -%>
           <main class="view-main">
		// DATA EVERY PAGE PAST HERE
	   </main>
	   <%- include('../_widgets/footer'); -%>
	</div>
	<%- include('../_widgets/scripts'); -%>
</body>
</html>

and include page data like this:

<%- include('../_pages/index'); -%>

And make then any number pages I want, how to make config for this?

Using EJS View Helpers

Hello,

Apologies if I'm bringing up a stupid thing, but I'm unable to get gulp to process any EJS view helpers. When I add <%= img_tag('example.png') %> to a template, for example, I get " img_tag is not defined". Same for all other view helpers. I'm able to pass variables and options in successfully, and I'm using the EJS 2.5.1. anyone else have this issue? Thanks!

An in-range update of mocha is breaking the build 🚨

The devDependency mocha was updated from 6.0.2 to 6.1.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

mocha is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v6.1.0

6.1.0 / 2019-04-07

πŸ”’ Security Fixes

  • #3845: Update dependency "js-yaml" to v3.13.0 per npm security advisory (@plroebuck)

πŸŽ‰ Enhancements

  • #3766: Make reporter constructor support optional options parameter (@plroebuck)
  • #3760: Add support for config files with .jsonc extension (@sstephant)

πŸ“  Deprecations

These are soft-deprecated, and will emit a warning upon use. Support will be removed in (likely) the next major version of Mocha:

πŸ› Fixes

  • #3829: Use cwd-relative pathname to load config file (@plroebuck)
  • #3745: Fix async calls of this.skip() in "before each" hooks (@juergba)
  • #3669: Enable --allow-uncaught for uncaught exceptions thrown inside hooks (@givanse)

and some regressions:

πŸ“– Documentation

πŸ”© Other

  • #3830: Replace dependency "findup-sync" with "find-up" for faster startup (@cspotcode)
  • #3799: Update devDependencies to fix many npm vulnerabilities (@XhmikosR)
Commits

The new version differs by 28 commits.

  • f4fc95a Release v6.1.0
  • bd29dbd update CHANGELOG for v6.1.0 [ci skip]
  • aaf2b72 Use cwd-relative pathname to load config file (#3829)
  • b079d24 upgrade deps as per npm audit fix; closes #3854
  • e87c689 Deprecate this.skip() for "after all" hooks (#3719)
  • 81cfa90 Copy Suite property "root" when cloning; closes #3847 (#3848)
  • 8aa2fc4 Fix issue 3714, hide pound icon showing on hover header on docs page (#3850)
  • 586bf78 Update JS-YAML to address security issue (#3845)
  • d1024a3 Update doc examples "tests.html" (#3811)
  • 1d570e0 Delete "/docs/example/chai.js"
  • ade8b90 runner.js: "self.test" undefined in Browser (#3835)
  • 0098147 Replace findup-sync with find-up for faster startup (#3830)
  • d5ba121 Remove "package" flag from sample config file because it can only be passes as CLI arg (#3793)
  • a3089ad update package-lock
  • 75430ec Upgrade yargs-parser dependency to avoid loading 2 copies of yargs

There are 28 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Report more details on error

Currently, when the ejs processing fails (like from a syntax error), the generated error event only reports an error message like Error: Could not find matching close tag for "<%=".

It would be nice to have the file name too so the developer knows where to search for the error in case the same stream handles several ejs files. Having the line number and column would be perfect.

Ideally, those extra details should be included in separate error object fields rather than in the error message string.

Access to ejs global object

Currently there is no way to change the settings for ejs, for things like custom delimiters or fileLoader

An in-range update of prettier is breaking the build 🚨

The devDependency prettier was updated from 1.18.0 to 1.18.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

prettier is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for 1.18.1

πŸ”— Changelog

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Don't use ejs.render when options.client is true

Tried to use this to compile clientside templates, but since it uses ejs.render, it will throw an error on various undefined variables during compilation. I can't provide browser variables - the plugin should use ejs.compile if it sees options.client is set to true.

gulp-ejs library objective

What is the purpouse of gulp-ejs. I look at the documentation but i don't understand what problem it solves.

Thanks

Problem with root option

Hello, first of all thanks for the plugin. When i'm trying to set root option via options, seems that ejs don't get it. I'm started to search about this problem and found that mde/ejs#221

Some options blacklisted from opts-in-data and root options seems too :( https://github.com/mde/ejs/releases/tag/v2.5.3

Suppose that now we need third parameter with options for ejs.
Or maybe i misunderstand something?

Set root in options for absolute include paths

I can't seem to get the root option working with gulp. I get this error:
Error: ENOENT: no such file or directory, open \'/partials/header.ejs\'

Would be really nice to keep includes absolute and not write out the relative paths in every include.

one template and array of object

Hi,
if I have a template, then an array of objects:

var params = [{name:'n1', age:30, file:'f1.html'}, {name:'n2', age:20', file:'f2.html'}]

how to apply the params to a single template to generate f1.html and f2.html?

Setting `ext` doesn't change files extensions

Here my gulp task. I expect compiled file will have the html extension, but it still have ejs. What I do wrong?

return gulp
    .src(config.html.from)
    .pipe(
      $.ejs({
        message: 'Hello Gulp!',
        ext: '.html',
      }).on('error', $.util.log),
    )
    .pipe(gulp.dest(config.html.to));
});

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.