像在 php 中一样在 nodejs 中渲染 html

Alt*_*ime 5 php node.js server-side-rendering

这似乎是一个简单的问题,但我在 google 或 stackoverflow 中找不到任何关于它的信息。可能我没有找到正确的关键字。

在php中你可以写这样的东西

例子.php

<?php
//a bunch of sloppy logic, or maybe some includes but for this I'll just define the variables below...
  $title = "Word to your mother";
  $heading = "Too legit";
  $paragraph = "Extensive research has shown that people's taste in music stops changing once they are forced to earn a living. Maybe that's when they learn how dumb the lyrics really are or maybe they don't have time to waste on things that no longer matter...";
?>
<!DOCTYPE html>
<html>
 <head>
  <title><?=$title?></title>
 </head>
 <body>
  <h1><?=$heading?></h1>
  <p><?=$paragraph?></p>
  <h2>Counting</h2>
  <?php
    for($x=1;$x<=10;$x++){
  ?>
    <p><?=$x?></p>
  <?php
    }
  ?>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

在 nodejs 中是否有一些等价物?

更广泛的问题与从浏览器视为静态的 nodejs 服务器提供动态内容有关。在客户端需要任何类型的 JavaScript 的解决方案对我不起作用。

我看到了 ejs 和 vue,但它们都<script src='source.js'>在 DOM 上有类似的东西,这正是我不想要和不能拥有的。

如果您认为这是重复的,请在评论中说出来,并在将其标记为重复之前给我一次澄清的机会。

澄清/更新:

术语“模板”可能是我试图描述的功能的否定关键字。在上面的 php 示例中,我可以在 if 语句或循环中嵌套一个 html 元素,同时保持服务器标记内联。还有另一篇文章在这里那里的问题主要问了同样的事情,但答案并不令人满意远程。

Alt*_*ime 3

谢谢乔桑和奥斯汀。我阅读了 ejs.co 和文档,但在他们的页面上找不到我在说什么。乔桑在他的评论中描述说它可以遵循循环和条件,但我不明白如何做到。下面没有我包含的任何示例。

最终我遇到了How to: Use ejs without express,它只是将渲染吐到控制台。这是我在最初的问题中使用的相同的 php 示例,但我认为以尽可能最少的方式完全在 node.js 中完成。

服务器.js

const http = require('http');
var ejs = require('ejs');
var fs = require('fs');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
var htmlContent = fs.readFileSync(__dirname + '/main.ejs', 'utf8');
var htmlRenderized = ejs.render(htmlContent, {filename: 'example.ejs'});

  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  res.end(htmlRenderized);
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Run Code Online (Sandbox Code Playgroud)

示例.ejs:

<%
  var title = "Word to your mother";
  var heading = "Too legit";
  var paragraph = "Extensive research has shown that people's taste in music stops changing once they are forced to earn a living. Maybe that's when they learn how dumb the lyrics really are or maybe they don't have time to waste on things that no longer matter...";
%>

<!DOCTYPE html>
<html>
 <head>
  <title><%=title%></title>
 </head>
 <body>
  <h1><%=heading%></h1>
  <p><%=paragraph%></p>
  <h2>Counting</h2>
  <%
    for(x=1;x<=10;x++){
  %>
    <p><%=x%></p>
  <%
    }
  %>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

当然,方法中标题、标题和段落的值ejs.render如果包含在传递的对象中,这是您在查找 ejs 示例时通常会看到的示例。