質問

I wonder if it's possible to do a double rendering with ejs with different tags.

For example I've got this ejs template

<@= test @>

<% for(var i=0; i<people.length; i++) { %>
    <li>
        <%= people[i].name %>
    </li>
<%
    }
%>

In node.js I'm rendering either with the default tags (<%) or with some defined tags (<@) like this

var people = [{"name":"Martin"}, {"name":"Jean"}];

 exports.test = function(req, res) {
    res.render('template', {
        open:'<@',close:'@>',
        people : people,
        test : "Hello world"
    })
}

This code will render

Hello world <% for(var i=0; i
<%= people[i].name %>
<% } %>

And this one

var people = [{"name":"Martin"}, {"name":"Jean"}];

 exports.test = function(req, res) {
    res.render('template', {
        people : people,
        test : "Hello world"
    })
}

will render

<@= test @>
Martin
Jean

And I'd like to find a way to double render it like this:

Hello world
Martin
Jean

Thanks

SOLUTION thanks to bnuhero

 exports.test = function(req, res) {
 var people = [{"name":"Martin"}, {"name":"Jean"}];
     res.render( 'test',
          {open:'<@', close:'@>', test : "Hello world"},
          function(err, html) {
            if (err) {
            console.log(err);
              res.send(500, err);
            } else {
              res.send(require('ejs').render(html, {people: people}))
            }
         });
    };
役に立ちましたか?

解決

First, call res.render() by providing a callback function. Both the possible error and the rendered string are passed to this callback function. res.render() won't perform automated response to the client side.

Second, apply require('ejs').render() to the rendered string in the callback function.

Finally, send the result to the client side.

exports.test = function(req, res) {
  var people = [{"name":"Martin"}, {"name":"Jean"}];
  res.render( 'template',
              {open:'<@', close:'@>', test : "Hello world"},
              function(err, html) {
                if (err) {
                  res.send(500, err);
                } else {
                  res.send(require('ejs').render(html, {people: people}));
                };
             });
};
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top