2013-05-04 79 views
0

我一直在使用Express web framework作爲Node.JS,並且一直使用降價解析器chjj/marked來解析縮減爲HTML。我也可以使用Express進行降價。我通常在我的Express項目中使用EJS模板,我希望能夠做的是使用EJS降價。如何使用Express/Node.JS使用EJS進行降價?

理想情況下,我想能夠使用的編譯時包括在EJS正常使用,這裏顯示其中的一個例子:

<% include header.html %> 

<h3>User List -- Located in users.html</h3> 
<ul id="users"> 
    <% users.forEach(function(user){ %> 
    <li><%= user.name %> -- <%= user.email %></li> 
    <% }) %> 
</ul> 

<% include footer.html %> 

這將是很好,如果我能有降價文件以及與內我EJS模板類似以下內容:

<% include markdown-file.md %> 

這也將是不錯的能夠使用降價中EJS語法或提供降價中訪問這些變量的一些方法。有這樣的可能嗎?如果不是,我最簡單的方法是在EJS模板中爲我的內容使用減價嗎?

編輯5/19/13:我真的很想做這樣的事情在我自己的項目中使用,所以我不得不放棄結合降價與EJS。看看我在GitHub上的模塊,名爲markedejs,如果你也對此感興趣,那麼README解釋我做得很好。此模塊使用marked爲了解析HTML到標記,unescape它,並將HTML模板傳遞給EJS進行最終呈現。所有EJS語法都可以在markdown中使用,並且在markdown模板中包含一個HTML模板也可以。您可以降價模板看起來像以下:

<nop><% include header.html %></nop> 

<%= site.title %> 
======================= 

<%= site.description %> 

This project was created by <%= author.name %>. My website is 
located at the url [<%= author.url %>](). 

## <%= header %> 

![Markdown Logo](img/mdlogo.png) 

Hey <%= user.name %>! This is a test template for the `markedejs` module. We 
can use markdown and EJS together for some pretty awesome results. 

### The Classic EJS Supplies List 
<ul> 
<% for (var i = 0; i < supplies.length; i++) { %> 
    <li><%= supplies[i] %></li> 
<% } %> 
</ul> 

### Your User Data 

I like using markdown lists a whole lot better when I can. 

- **Username:** <%= user.username %> 
- **Name:** <%= user.name %> 
- **Stars:** <%= user.stars %> 

We can do some conditionals as well. You will only see the footer below this 
paragraph if you pass in `true` for the `showFooter` flag. 

<% if (showFooter !== undefined && showFooter === true) { %> 
    <%= footer %> 
<% } %> 

<nop><% include footer.html %></nop> 
  • <nop>標籤被取下markedejs並被列入降價模板,以便<p>標籤不在身邊的header.htmlfooter.html內容加入。

然而,這並不完全做什麼我本來想的是,我希望能夠include降價模板雙方其他HTML模板等降價模板中。目前,我只能在我的降價模板中包含HTML模板。仍然希望任何人都可以有更好的想法,我可以如何使EJS包括減價文件的工作?

回答

2

你可能需要修改EJS如果你想獲得它處理的降價文件,在它的

<% include filename.ext %> 

指令。它們處理包含的方式很簡單並且是遞歸的,但它需要明確的降價文件知識,並且在將標記添加到模板之前調用降價轉換器來生成html。

我用marked創建我傳遞給我的EJS模板的功能,它可以調用包括一個降價文件,它工作得很好:

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

    // Allow the docs.html template to 'include' markdown files 
    var marked = require ('marked'); 

    var md = function (filename) { 
     var path = __dirname +"/views/docs/" + filename; 
     var include = fs.readFileSync (path, 'utf8'); 
     var html = marked (include); 

     return html; 
    }; 

    res.render ('docs', {"md": md}); 
}); 

在模板中,做到這一點:

<%- md("index.md") %> 

,但它不會讓我使用EJS模板函數的降價文件,降價是獲取內聯純HTML。