2017-11-20 5 views
0

일부 NodeJ를 배우기 시작했고 작은 라우팅을 만들고 싶습니다. 그래서 지금과 변수를 처리 할 것입니다 내 index.pug 파일이 템플릿 include을 사용 NodeJs의 인덱스 파일에서 pug 템플릿으로 데이터 전달하기

var express = require('express'); 
var app = express(); 

app.get('/profile/:id', function (req, res) { // The URL for localhost:8888/profile/Peter 

    var user = null; // Read some data from the JSON file later on... 

    res.render('index', { // Load the index file and set some variables 
    content: 'Views/profile.pug' 
    name: user.name, 
    hitpoints: user.hitpoints, 
    stamina: user.stamina, 
    strength: user.strength }); 
}); 

app.listen(8888, function() { 
    console.log('Server listening on Port 8888'); 
}); 

html 

    link(rel='stylesheet', href='/CSS/requirements.css') 
    script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js") 

    body 
    p 'TEST - This is on all pages' 

    include content 

그래서 내 템플릿은 사용자 변수를 필요로로드 내 server.js 여기이 코드를 사용 서버에서

script(src="/Client/profile.js") 

p 'Character:' 
p = name 

p 'Hitpoints:' 
p = hitpoints 

p 'Stamina:' 
p = stamina 

p 'Strength:' 
p = strength 

button(class='btn' onclick='back()') 'Back' 

어떻게이 index.pug 포함되는 파일 index.pug에서 정보를 얻을 수 및 템플릿에 보낼 수 있습니까? include content // and pass the needed variables

+0

색인에서 정보를 보낼 수 있도록, "index.pug에서 정보를 얻을" .pug 서버에? 아니면, pug 템플릿이 JSON 값 (var 사용자)을 서버에서 렌더링하지 않는다는 것을 의미합니까? – LMokrane

+0

방금 ​​내 게시물 – peterHasemann

답변

0

처럼

doctype html 
html 
    head 
    link(rel='styleshe... 

다음과 같은 몸의 부품을 교체하여 index.pughead.pug로 이름을 바꾸고 첫 선으로 추가

body 
    block content 

이제 새로운 파일을 생성 profile.pug 및 첫 번째 줄을 추가하십시오.

extends head.pug 
block content 
    script(src="/Client/profile.js") 

    p 'Character:' 

대신 index.pug 렌더링의 server.js에서

는, 렌더링 템플릿의 나머지 profile.pug

res.render('profile', 
    name: user.name, 
    hitpoints: user.hitpoints, 
+0

을 업데이트 했으므로 인덱스 파일에서 템플릿 파일로 변수를 보낼 수 있습니까? – peterHasemann

+0

express는'user' 변수의 값으로 템플릿을 렌더링합니다 – LMokrane

+0

hm 정말입니까? 일반적으로 나는 1 개의 색인 파일을 가지고 있고 그것에 몇몇 템플렛을 적재 할 것입니다. 여기에 템플릿에 인덱스를로드합니다. 잘 모르겠습니다 : / – peterHasemann

관련 문제