4

是否有用于 node.js 的库来“解析”具有特定语法的文件内容?例如,我有一个文件要在我的 node.js 服务器上提供:

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

然后它返回一个 HTML 文档:

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

我不知道如何更准确地描述它,比如 PHP 用于 Apache 服务器,但用于 node.js 服务器。

4

5 回答 5

4

EJS 模板的外观和感觉类似于 PHP 和 ASP,但它们是纯 JS:https ://ejs.co/

他们的例子:

<ul>
<% for(var i=0; i<supplies.length; i++) {%>
   <li><%= supplies[i] %></li>
<% } %>
</ul>
于 2013-08-09T13:06:21.450 回答
4

只需使用CGI-Node。它允许您像 PHP 一样在任何 Web 主机上运行 Node.js:

<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>
于 2016-10-18T22:21:13.477 回答
2

您可以使用下划线模板。它允许您编写这样的模板:

<ul>
<% _.each(people, function(name) { %>
  <li><%= name %></li>
<% }); %>
</ul>
于 2013-08-09T13:06:13.030 回答
2

您正在谈论模板引擎。有很多可能性,最流行的一种是

http://jade-lang.com/

与Express 框架集成时特别好。您可以在此处找到大量模板引擎:

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

于 2013-08-09T12:46:02.293 回答
-2

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.

于 2016-01-08T09:45:06.717 回答