You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js入门疑问:如何像PHP那样创建动态网页?

How to Create Dynamic Web Pages with Node.js (Like PHP's Embedded Code)

Hey there! As someone who made the switch from PHP to Node.js early on, I totally get that urge to replicate that "write code right in your HTML" workflow you’re used to. Let me break down exactly how to do this in Node.js, with a hands-on example that’ll feel familiar.

The Core Idea: Template Engines

Unlike PHP, where your web server directly parses files with embedded <?php ?> code, Node.js relies on template engines to mix JavaScript logic with HTML. These engines let you embed dynamic code in your markup, just like PHP—some even use syntax that’s nearly identical.

My Top Pick for PHP Devs: EJS

EJS (Embedded JavaScript) is perfect because its syntax mirrors PHP’s almost exactly. Let’s walk through setting it up step by step:

  1. Set Up Your Node.js Project
    First, create a new folder, open it in your terminal, and initialize a project:

    npm init -y
    

    Then install the two packages we need: Express (to handle web requests) and EJS (the template engine):

    npm install express ejs
    
  2. Create Your Express Server
    Make a file called app.js with this code:

    const express = require('express');
    const app = express();
    
    // Tell Express we're using EJS as our template engine
    app.set('view engine', 'ejs');
    // Optional: Specify where your template files live (defaults to a "views" folder)
    app.set('views', './views');
    
    // Define a route that renders a dynamic page
    app.get('/', (req, res) => {
      // Pass dynamic data to the template
      const dynamicData = {
        pageTitle: 'My Node.js Dynamic Page',
        username: 'Guest',
        items: ['Learn Node.js', 'Master EJS', 'Build Cool Apps']
      };
      // Render the "index.ejs" template with our data
      res.render('index', dynamicData);
    });
    
    // Start the server
    app.listen(3000, () => {
      console.log('Server running on http://localhost:3000');
    });
    
  3. Create Your EJS Template
    Make a folder called views, then inside it create index.ejs. This is where you’ll mix HTML and JavaScript, just like PHP:

    <!DOCTYPE html>
    <html>
    <head>
      <title><%= pageTitle %></title>
    </head>
    <body>
      <h1>Welcome, <%= username %>!</h1>
    
      <h2>Your To-Do List:</h2>
      <ul>
        <% items.forEach(item => { %>
          <li><%= item %></li>
        <% }) %>
      </ul>
    
      <% if (username === 'Admin') { %>
        <p>You have admin privileges!</p>
      <% } else { %>
        <p>You can upgrade to admin for more features.</p>
      <% } %>
    </body>
    </html>
    

    Notice the syntax:

    • <%= variable %> outputs the value (like <?php echo $variable; ?>)
    • <% code %> runs JavaScript logic without outputting (like <?php // logic here ?>)
  4. Run Your Server
    Back in the terminal, run:

    node app.js
    

    Open your browser and go to http://localhost:3000—you’ll see a fully dynamic page, just like you’d get with PHP!

Other Template Engines to Explore

If you want to try something different, here are a few popular options:

  • Handlebars: Uses {{ variable }} for output and helpers for logic, great for clean markup.
  • Pug (formerly Jade): Uses indentation instead of closing tags, more concise but has a steeper learning curve.
  • Nunjucks: Similar to Handlebars but with more flexibility, supported by Mozilla.

Key Difference from PHP

Remember: In PHP, the server parses your .php files directly when a request comes in. In Node.js, your Express server first processes the request (runs any backend logic), then passes data to the template engine, which generates the final HTML to send back to the client. It’s a slightly different flow, but the end result is the same—dynamic, data-driven web pages.

Hope this helps you get started! Let me know if you hit any snags along the way.

内容的提问来源于stack exchange,提问作者AliAbbas Bhojani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:12:28