2015-12-02 6 views
2

Я чтение файла синхронно и отправки содержимого переменной:Rendering переменной в шаблоне EJs

// Load the fs (filesystem) module 
var fs = require('fs'); 

// Read the contents of the file into memory. 
var text = fs.readFileSync('testfile.txt').toString() 

// index page 
app.get('/', function(req, res) { 
    res.render('index', { var: text }); 
}); 

app.listen(8080); 
console.log('8080 port'); 

Тогда в моих EJS файл (index.ejs) я вставил переменную так:

<main> 
     <div class="jumbotron"> 
      <h2><%= text %></h2> 
     </div> 
    </main> 

Я получаю эту ошибку, что «текст» не ссылается:

>> 14| <h2><%= text %></h2> 
    15|   </div> 
    16|  </main> 
    17|  </footer> 

text is not defined 

Как вы оказываете переменной в EJs?

+0

Хорошо, я понял. :) Я удалил ключевое слово var из объявления текстовой переменной, а затем также изменил часть res.render: text = fs.readFileSync ('testfile.txt'). ToString() // индексная страница приложение. get ('/', function (req, res) { res.render ('index', {text}); }); –

ответ

2
// Load the fs (filesystem) module 
var fs = require('fs'); 

// Read the contents of the file into memory. 
var text = fs.readFileSync('testfile.txt').toString() 

// index page 
app.get('/', function(req, res) { 
res.render('index', { text: text }); 
}); 

app.listen(8080); 
console.log('8080 port'); 

Не удаляйте уаг ключевое слово из объявления переменного вместо удалить ключевое слово уага при визуализации страницы в текст ..

И он должен работать.

Смежные вопросы