Nice programing

Node.js-EJS-부분 포함

nicepro 2020. 12. 28. 22:32
반응형

Node.js-EJS-부분 포함


노드에 Embedded Javascript 렌더러를 사용하려고합니다 : https://github.com/visionmedia/ejs

.ejs 뷰 파일 내에 다른 뷰 파일 (부분)을 포함 할 수있는 방법을 알고 싶습니다.


Express 3.0 사용 :

<%- include myview.ejs %>

경로는로 설정된보기 디렉토리가 아니라 파일을 포함하는 호출자로부터 상대적입니다 app.set("views", "path/to/views").

EJS에는


Express에서는 4.x다음을 사용하여로드했습니다 ejs.

  var path = require('path');

  // Set the default templating engine to ejs
  app.set('view engine', 'ejs');
  app.set('views', path.join(__dirname, 'views'));

  // The views/index.ejs exists in the app directory
  app.get('/hello', function (req, res) {
    res.render('index', {title: 'title'});
  });

그런 다음 작동하려면 두 개의 파일이 필요합니다 views/index.ejs.

<%- include partials/navigation.ejs %>

그리고 views/partials/navigation.ejs:

<ul><li class="active">...</li>...</ul>

Express ejs에 html 템플릿 을 사용하도록 지시 할 수도 있습니다 .

var path = require('path');
var EJS  = require('ejs');

app.engine('html', EJS.renderFile);

// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
  res.render('index.html', {title: 'title'});
});

마지막으로 ejs레이아웃 모듈을 사용할 수도 있습니다 .

var EJSLayout = require('express-ejs-layouts');
app.use(EJSLayout);

views/layout.ejs레이아웃으로 를 사용합니다 .


Express 4.x 기준

app.js

// above is all your node requires

// view engine setup
app.set('views', path.join(__dirname, 'views')); <-- ./views has all your .ejs files
app.set('view engine', 'ejs');

error.ejs

<!-- because ejs knows your root directory for views, you can navigate to the ./base directory and select the header.ejs file and include it -->

<% include ./base/header %> 
<h1> Other mark up here </h1>
<% include ./base/footer %>

Express 3.x no longer support partial. According to the post ejs 'partial is not defined', you can use "include" keyword in EJS to replace the removed partial functionality.


Try to use the whole path ==>

<% include C:/Users/UserName/Desktop/NodeJS/partials/header.ejs %> ---> pay attention to '/'

Tried this with node --version v8.11.4 + express module v.4.x


EJS by itself currently does not allow view partials. Express does.

ReferenceURL : https://stackoverflow.com/questions/5404830/node-js-ejs-including-a-partial

반응형