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

寻求PHP中require_once式页面复用的JavaScript等效方案

Equivalent of PHP's require_once for Base HTML Structure in JavaScript

Nice question! I’ve made this exact transition from PHP to JavaScript before, so I can walk you through the best equivalent approaches depending on your project setup:

1. Pure Static Frontend (No Build Tools)

If you’re working with plain HTML/JS without a build pipeline, you can create a reusable function to inject your base structure into each page.

First, create a docStart.js file with your base template logic:

// docStart.js
export function renderDocStart(pageTitle = "My Website") {
  const baseStructure = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>${pageTitle}</title>
      <!-- Add global styles, fonts, or scripts here -->
    </head>
    <body>
  `;
  // Inject the structure at the start of the document
  document.write(baseStructure);
}

Then, in every page you want to use this, import and call the function early in the document:

<!-- index.html -->
<script type="module">
  import { renderDocStart } from './docStart.js';
  // Pass a custom title for this page
  renderDocStart("Home Page");
</script>

<!-- Your page-specific content goes here -->
<h1>Welcome to the Home Page!</h1>
<p>This is my main content.</p>

<!-- Close the open tags from the base structure -->
<script>
  document.write('</body></html>');
</script>

Note: document.write works here because we’re calling it during initial page load. Avoid using it after the page has finished rendering, as it will overwrite the entire document.

2. Modern Frontend with Build Tools (Vite, Webpack, etc.)

If you’re using a build tool like Vite or Webpack, you have cleaner options using template partials or framework components.

Option A: Raw HTML Imports (No Framework)

Create a doc-start.html file with your base structure:

<!-- doc-start.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>{{title}}</title>
</head>
<body>

In your JavaScript, import the HTML as a raw string and replace placeholders:

// Import the raw HTML string (Vite uses ?raw suffix; Webpack needs a loader)
import docStart from './doc-start.html?raw';

function renderFullPage(pageTitle, pageContent) {
  // Replace the title placeholder and add closing tags
  const fullHtml = docStart.replace('{{title}}', pageTitle) + pageContent + '</body></html>';
  
  // If you're server-side rendering, send this string as the response
  // If client-side, you can use it to replace the document content in an SPA
  document.documentElement.innerHTML = fullHtml;
}

// Usage for the home page
renderFullPage("Home Page", "<h1>Welcome Home!</h1>");

Option B: Framework Layout Components (React/Vue/Svelte)

If you’re using a frontend framework, create a reusable Layout component that wraps your page content:

// React example: components/Layout.jsx
export default function Layout({ title, children }) {
  return (
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta httpEquiv="X-UA-Compatible" content="ie=edge" />
        <title>{title}</title>
      </head>
      <body>{children}</body>
    </html>
  );
}

Then use it in every page component:

// pages/Home.jsx
import Layout from '../components/Layout';

export default function Home() {
  return (
    <Layout title="Home Page">
      <h1>Welcome to the Home Page!</h1>
      {/* Page-specific content here */}
    </Layout>
  );
}

3. Node.js Backend (Express, etc.)

If you’re using Node.js for server-side rendering (like PHP), use a template engine that supports partials or inheritance. EJS is a popular choice that feels similar to PHP:

First, create a partial for your base structure:

<!-- views/partials/doc-start.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= title %></title>
</head>
<body>

Then include it in your page templates:

<!-- views/home.ejs -->
<%- include('partials/doc-start.ejs', { title: 'Home Page' }) %>

<h1>Welcome to the Home Page!</h1>
<p>This is server-rendered content.</p>

</body>
</html>

In your Express server, configure EJS and render the page:

// server.js
const express = require('express');
const app = express();

// Set EJS as the template engine
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.render('home'); // Renders home.ejs with the included partial
});

app.listen(3000);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:56:28