Coder Social home page Coder Social logo

ejs-mate's Introduction

ejs-mate

Status

npm version Node.js CI codecov

About

Express 4.x layout, partial and block template functions for the EJS template engine.

Previously also offered include but you should use EJS 1.0.x's own directive for that now.

Installation

$ npm install ejs-mate --save

(--save automatically writes to your package.json file, tell your friends)

Usage

Run node app.js from examples and open localhost:3000 to see a working example.

Given a template, index.ejs:

<% layout('boilerplate') -%>
<h1>I am the <%= what %> template</h1>

And a layout, boilerplate.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title>It's <%= who %></title>
  </head>
  <body>
    <section>
      <%- body -%>
    </section>
  </body>
</html>

When rendered by an Express 4.0 app:

var express = require('express'),
  engine = require('ejs-mate'),
  app = express();

// use ejs-locals for all ejs templates:
app.engine('ejs', engine);

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')

// render 'index' into 'boilerplate':
app.get('/',function(req,res,next){
  res.render('index', { what: 'best', who: 'me' });
});

app.listen(3000);

You get the following result:

<!DOCTYPE html>
<html>
  <head>
    <title>It's me</title>
  </head>
  <body>
    <section>
      <h1>I am the best template</h1>
    </section>
  </body>
</html>

Note, if you haven't seen it before, this example uses trailing dashes in the EJS includes to slurp trailing whitespace and generate cleaner HTML. It's not strictly necessary.

Features

layout(view)

When called anywhere inside a template, requests that the output of the current template be passed to the given view as the body local. Use this to specify layouts from within your template, which is recommended with Express 3.0, since the app-level layout functionality has been removed.

partial(name,optionsOrCollection)

When called anywhere inside a template, adds the given view to that template using the current given optionsOrCollection. The usual way to use this is to pass an Array as the collection argument. The given view is then executed for each item in the Array; the item is passed into the view as a local with a name generated from the view's filename.

For example, if you do <%-partial('thing',things)%> then each item in the things Array is passed to thing.ejs with the name thing. If you rename the template, the local name of each item will correspond to the template name.

block('name')

Calling block('name') creates the named block if it doesn't exist, and then returns an object with append(), prepend(), replace(), and toString().

Basic usage:

body-template.ejs

<% layout('boilerplate') -%>
<% block('head').append('<link type="text/css" href="/foo.css">') %>
<h1>I am the template</h1>
<% block('footer').append('<script src="/bar.js"></script>') %>

And a layout, boilerplate.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title>I'm the layout</title>
    <%- block('head').toString() %>
  </head>
  <body>
    <section>
      <%-body -%>
    </section>
    <%= block('footer').toString() %>
  </body>
</html>

Running Tests

To run the test suite first invoke the following command within the repo, installing the development dependencies:

$ npm install -d

then run the tests:

$ npm test

Whither Include?

We upgrade EJS to v3.x, it used as a method now:

<%- include('path/view') %>

Credits

This library is a fork from Robert Tom Carden's ejs-locals, and the partial function remains relatively untouched from there (aside from cache support). Robert is still updating his library and it now supports other template engines - check it out!

License

(The MIT License)

Copyright (c) 2012 Robert Sköld [email protected]

Copyright (c) 2012 Tom Carden [email protected]

Copyright (c) 2014 Jackson Tian [email protected]

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.

ejs-mate's People

Contributors

duereg avatar jacksontian avatar nax3t avatar nfriedly avatar randometc avatar slaskis avatar timothygu 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

ejs-mate's Issues

bump version?

Could you bump the version and publish the new version? I would like access to the code I added to the PR

EJS 2.0.0 support

right now this package is hardcoded for ejs 1.0.0

in my case i'm trying to use variables with ejs's "include" which is not available until ejs 2.0.0

that's why i need ejs 2.0.0 support

Support for res.write()

I basically need exactly what you've already done for res.render() to work with res.write(). Is that something you're willing to do?

Feature request: partial paths to also look at relative path from app.set('views')

Would you be interested in having partial paths also look at paths relative to the app.set('views') if the partial isn't found relative to the file first? This would allow two nice features:

  1. Deeply nested view directories can access partials without having to put in back directories.
  2. With app.set('views') now being an array, accessing partials in a separate view path is also easier.

If you like the idea, I can write up a pull request with it along with the appropriate tests.

ejs-mate Whitespace-trim mode of EJS

Hi,

I'm wondering if the tag <%_ used in EJS to trim whitespaces is supported by ejs-mate ? Since i'm having an issue with this tag in one of my views. Putting a for loop after opening this <%_ telling me:

"SyntaxError: Unexpected token for (...)"

Block

Adding

<%= block('javascripts') %>

To the layout.ejs

And

<% block('footer').append('<script src="/bar.js"></script>') %>

To a page.ejs that extends the layout will add text to the page in the following format:

&lt;script src=&quot;/bar.js&quot;&gt;&lt;/script&gt;

Am I doing something wrong here?
Thanks.

Making this EJS 2.0.0 compatible

I'd like to make this repo work with EJS 2.0.0. I figured out the changes that would need to happen to make that work so would be more than happy to make a PR.

Would you be interested in supporting EJS 2.0.0? And if so, would you be ok with a breaking change and a major version bump, as well as dropping EJS 1.0.0 support from master? Or if you'd prefer, I can make it support both EJS versions, but it'll basically have to bring back the options.__proto__ magic that EJS 1.0.0 did but that EJS 2.0.0 no longer does.

layout not defined

i'm getting this error
ReferenceError: C:\Users\OLYNSEC\ecommerce\views\home.ejs:1

1| <% Layout('boilerplate') -%>

2| 

3| 

4| <h1> shop smart, save big!</h1>

Layouts is not defined
at eval (eval at compile (C:\Users\OLYNSEC\ecommerce\node_modules\ejs\lib\ejs.js:549:12), :9:8)
at returnedFn (C:\Users\OLYNSEC\ecommerce\node_modules\ejs\lib\ejs.js:580:17)
at tryHandleCache (C:\Users\OLYNSEC\ecommerce\node_modules\ejs\lib\ejs.js:223:34)
at View.exports.renderFile [as engine] (C:\Users\OLYNSEC\ecommerce\node_modules\ejs\lib\ejs.js:437:10)
at View.render (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\view.js:127:8)
at tryRender (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\application.js:640:10)
at EventEmitter.render (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\response.js:971:7)
at C:\Users\OLYNSEC\ecommerce\server.js:46:7
at Layer.handle [as handle_request] (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\OLYNSEC\ecommerce\node_modules\express\lib\router\index.js:275:10)

can someone help me using latest version of nodejs thank you ahead

layout changes to _layoutFile

I saw this in the index.js file:
// for backward-compatibility, allow options to
// set a default layout file for the view or the app
// (NB:- not called layout any more so it doesn't
// conflict with the layout() function)
when use res.render function, the paramter {layout:'layout'} changes to {_layoutFile:'layout'}
it's important message,but I can't see it in the documents,why not add it to the readme.md file

partial can't use the path which in express sets

Like that:

/app.js/

var app = express();
var express = require('express');
var ejsMate = require('ejs-mate');
var path = require('path');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('ejs',ejsMate);

we set the static path at views

catalogue:

|---views
| |---src
| | |---list.ejs
| | |---main.ejs
| |---layout
| | |---layout.ejs
/main.ejs*/

<% layout('/layout/layout') %>
<%- partial('/src/list',{name:"abc"}) %>

layout true but partial is wrong which consoles that could not find the path

why?

Unable to utilize EJS's include while using ejs-mate.

In the EJS-Mate readme, it is recommended that we utilize EJS includes; however unless I've configured something incorrectly I am unable to call <%- include('template',{local:'values'}) %>, instead getting an error: "Unable to find "('template',{local:'values'}).ejs"

However this works:
`<% local = 'values' %>
<%- include template %>

It doesn't seem to matter what I do. Am I missing some kind of obvious option to turn of EJS-mate's include? I'd prefer to use the EJS but I'm some what new to both EJS & EJS-Mate.

How to add a filter

If I want to add a filter in ejs, I can to it like this:

ejs.filters.last = function(obj) {
  return obj[obj.length - 1];
};

But if I want do it with ejs-mate, how to do this?

Layout undefined?

I have a simple EJS template:

<% layout('layout') -%>
<section class="content">
    <div ng-view>
        <h2><%= mongoFormName %></h2>
    </div>
</section>

But I am getting an error:

ReferenceError: H:\building-angularjs-nodejs-apps-mean\3-building-angularjs-node
js-apps-mean-m3-exercise-files\FormManager\form-manager\server\views\index.ejs:1

 >> 1| <% layout('layout') -%>
    2| <section class="content">
    3|  <div ng-view>
    4|          <h2><%= mongoFormName %></h2>

layout is not defined

Is it the keyword 'layout' that is undefined? I changed the argument to 'layout' and I still got the error that 'layout is not defined'. So my conclusion is that the keyword layout is not defined. I think I followed the steps in the documentation:

var express = require('express'),
  engine = require('ejs-mate'),
. . . . 
app.engine('ejs', engine);

app.set('views', __dirname + '/server/views');
app.set('view engine', 'ejs');

Thank you.

In ubuntu, showing some error....

I followed every steps mentioned but then also its showing error and not get recognised as template..
In error shows its recognise it as "boilerplate.views" not as "boilerplate.ejs"..
Please help me,, what is the problem and where i am failing...
Screenshot from 2023-12-15 17-16-04

app.set('views') assumed to be string

If you set app.set('views', ['path1', 'path2']) (per the docs), the code throws an error when trying to call layout = join(options.settings.views, layout); as the code assumes that app.views is a string.

TypeError: Arguments to path.join must be strings
   at path.js:360:15
   at Array.filter (native)
   at exports.join (path.js:358:36)
   at /Users/lambertsteven/fs/snow/node_modules/ejs-mate/index.js:118:18
   at Object.exports.renderFile (/Users/lambertsteven/fs/snow/node_modules/ejs-mate/node_modules/ejs/lib/ejs.js:323:3)
   at View.module.exports [as engine] (/Users/lambertsteven/fs/snow/node_modules/ejs-mate/index.js:82:7)
   at View.render (/Users/lambertsteven/fs/snow/node_modules/express/lib/view.js:93:8)
   at EventEmitter.app.render (/Users/lambertsteven/fs/snow/node_modules/express/lib/application.js:566:10)
   at ServerResponse.res.render (/Users/lambertsteven/fs/snow/node_modules/express/lib/response.js:938:7)
   at /Users/lambertsteven/fs/snowApp/controllers/routes.js:3:9

EJS-Locals missing block, script, stylsheet

Hi,

Working well with Express 4.x but do you have plans to add block, script, stylsheet features ? It's very usefull to group stylesheet at the top of pages for instance.

update ejs version

According to a github notification i got, there seems to be a vulnerability in ejs version 1.0.0 so this dependency should be updated.

EJS Async

Hi,

I really like EJS template because it simple and readable, but do you have best practices to handle async code in templates ?

How to add multi-line script in partial view?

Hi,

Please help. I have this master.ejs layout :

<!DOCTYPE html>
<html>
<head>
<title>The title</title>
</head>

<body>
  <%- body %>

  <!--Lots of script-->
  <script src="/a.js"></script>
  <script src="/b.js"></script>
  <script src="/c.js"></script>
  <script src="/d.js"></script>

  <!--Additional script-->
  <%- block('script') %>
</body>
</html>

How do I add another multi-line long script inside block('script')? Consider I have this partial view :

<% layout('master') %>

<!-- For body -->
<div>BODY</div>

<!--For script -->
<% block('script').append("<script>") %>
<% block('script').append("console.log('hello world!');") %>
<% block('script').append("console.log('another line!');") %>
<% block('script').append("<script>") %>

It's less readable and very tedious. Also, I'm gonna need to inject variables to this JS. Any suggestion?

Thanks before!

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.