Are
Are

Reputation: 2241

Templating library for node.js with php-like syntax

Is there a library for node.js to "parse" a content of a file with specific syntax? In example, I have a file which I want to serve on my node.js server:

<!DOCTYPE html>
<html>
<head>...</head>
<body>
    <?node echo Date.getTime(); ?> <!-- or something like this, I hope you have got the idea -->
</body>
</html>

Then it returns a HTML document:

<!DOCTYPE html>
<html>
<head>...</head>
<body>
    08.08.2013 <!-- or something like this, I hope you have got the idea -->
</body>
</html>

I don't know how to describe it more precisly, something like PHP for Apache server, but for node.js server.

Upvotes: 4

Views: 3163

Answers (5)

SheetJS
SheetJS

Reputation: 22925

EJS templates look and feel like PHP and ASP but are pure JS: https://ejs.co/

Their example:

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

Upvotes: 4

niutech
niutech

Reputation: 29992

Just use CGI-Node. It allows you to run Node.js on any web hosting just like PHP:

<html>
    <head>
    </head>
    <body>
        <? var helloWorld = 'Hello World!'; ?>
        <?= helloWorld ?>
    <br>
    <b>I can count to 10: </b>
    <? for (var index = 0; index <= 10; index++) { ?>
        <?= index ?>
    <? } ?>
    </body>
</html>

Upvotes: 4

fis
fis

Reputation: 87

I might be a little late to the party, but I worked on something like this yesterday and it works surprisingly similar to php. E.g. you can do stuff like

<?j
include_once("header.jhtml");

for(var i = 0; i < 10; i++) { ?>
<span id="<?j print(i) ?>">

<?j}
print($.req.url);
include("footer.jhtml");
?>

which will include the header file (if it was not included before) just like in php and then print 10 spans with id's from 0 to 9, then print the request url ($ is the context variable which includes the request data), then include the footer file. So it's basically php with js syntax. I will make it available on npm probably this weekend. It's very much in it's early stage though, as I said, I worked 1 day on it.

Upvotes: -2

juandopazo
juandopazo

Reputation: 6329

You can use Underscore templates. It lets you write templates like this:

<ul>
<% _.each(people, function(name) { %>
  <li><%= name %></li>
<% }); %>
</ul>

Upvotes: 2

freakish
freakish

Reputation: 56587

You are talking about a template engine. There are many possibilites, one of the most popular is jade:

http://jade-lang.com/

It is especially good when integrated with Express frawework. You can find a big list of template engines here:

https://github.com/joyent/node/wiki/modules#wiki-templating

Upvotes: 2

Related Questions