使用Express/Node.JS,如何使用EJS呈现Markdown?

3
我一直在使用 Express web框架 来开发 Node.JS,并使用 markdown 解析器 chjj/marked 将 markdown 转换为 HTML。我也能够使用 Express 渲染此 markdown。通常在我的 Express 项目中,我使用 EJS 模板,我希望能够使用 EJS 和 markdown。
理想情况下,我希望能够使用编译时包含通常在 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模板中包含markdown文件,就像以下示例一样,那将是很好的:

<% include markdown-file.md %>

同时在 markdown 中使用 EJS 语法或提供一些访问 markdown 中变量的方式也是不错的选择。这样做是否可行?如果不行,那么最简单的方法是什么,我该如何在 EJS 模板中使用 markdown 来编写我的内容呢?编辑于 2013 年 5 月 19 日:我一直很想在自己的项目中使用类似的功能,所以我尝试将 markdown 与 EJS 结合起来。如果你也感兴趣,可以看看我在 GitHub 上的模块 markedejs,README 很好地解释了我所做的事情。该模块使用 marked 将 markdown 解析为 HTML,然后将 HTML 模板传递给 EJS 进行最终渲染。所有的 EJS 语法都可以在 markdown 中使用,并且在 markdown 模板中包含 HTML 模板也可以正常工作。你可以创建类似以下的 markdown 模板:
<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 移除,并包含在 markdown 模板中,以便 header.htmlfooter.html 的内容周围不会添加 <p> 标签。

但是,这还没有完全实现我最初想要的功能,我希望能够在其他 HTML 模板和其他 markdown 模板中包含 markdown 模板。目前,我只能在我的 markdown 模板中包含 HTML 模板。仍然希望有人能提供更好的想法,使 EJS 包含能够与 markdown 文件一起使用?


hexo 实现了这个功能,我会去看看他们是如何做到的。 - Kyle Baker
3个回答

5

如果您想让EJS处理markdown文件,您可能需要修改它。

<% include filename.ext %>

指令(directive)。它处理包含(includes)的方式是简单递归的,但需要明确了解markdown文件,并调用markdown转换器来生成html,然后再添加到模板中。

我使用了marked创建了一个函数,将其传递给我的EJS模板,可以调用该函数来 include 一个markdown文件,效果相当不错:

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") %>

但是我无法在Markdown文件中使用EJS模板函数,Markdown是纯HTML,会被内联。


3
请尝试将<%=更改为<%-。

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接