Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

node.js - I would like to be able to include EJS template data into a partial view and have it render on all pages the partial is called

I am working on layouts and templating. I have a site where I have files "views/partials/header.ejs" and "views/partial/footer.ejs". I have the app.js file with templating set up as follows:

const express = require('express')
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const ejs = require('ejs');
const date = require(__dirname + '/date.js');

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));


app.get('/', function(req, res) {

  const year = date.getYear();

  res.render('home', {copyrightYear: year})
});



app.listen(3000, function() {
  console.log('Server started on port 3000');
});

What I need to do is pass the const copyrightYear into the partial "footer" instead of having to to input into each route. Any advice would be welcomed.

Thanks in advance.

question from:https://stackoverflow.com/questions/65646018/i-would-like-to-be-able-to-include-ejs-template-data-into-a-partial-view-and-hav

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can't do that because when you make a request the server get the required file the does the logic on it and then it send it back to the browser .

so when you use this

app.get('/', function(req, res) {

  const year = date.getYear();

  res.render('home', {copyrightYear: year})
});

the server will get the home file which includes the partials files then pass the data then send it to the browser .

so you must make separate request for each file you want and then do the logic on it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...