Passing raw Markdown text to Jade

2019-03-10 20:30发布

问题:

I'm playing around with my first Node.js Express application, and as every programmer knows, the first thing you should build when testing out a new framework is a blog! Anyway, I'd like to write the articles in Markdown and then render it in the view. I saw that Jade allows for this to be done inside the view itself, using filters, but I can't get that working.

To simplify the situation, here's an example of what I'm talking about.

//app.js
res.render("article", {
    md : "Hello World!\n\n*Woo*"
});

//article.jade
section
    :markdown
        #{md}

But, that outputs this: <section><h1>{md}</h1></section>... it isn't substituting in the variables I've passed to it.

Then I tried this:

//article.jade
section
    :markdown
        !{md}

And the output is this:

<section><p>Hello World!

*Woo*</p></section>

So, now it's not parsing the markdown!

I have been able to get this to work by parsing the markdown in the app.js file and then passing the HTML to the view to display, but I dunno, that seems a bit messier.

Is there a way to pass variables into Jade filters?

回答1:

You can do this with a function passed in to jade from node:

var md = require("node-markdown").Markdown;

Then pass it into the view as a local:

res.render('view', { md:md, markdownContent:data });

Then render it in the jade view by calling the function:

!= md(markdownContent)


回答2:

The node module node-markdown is deprecated. The marked is advanced new version. You can try like this

var md = require('marked');

Inside your router

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

Inside your jade template

div!= md(note.string)


回答3:

I don't think jade can do this out of the box. One way to accomplish it that might feel slightly cleaner than pre-rendering the markdown is to create a helper function called markdown that takes a markdown string and returns HTML. Then you could do something like

section
    != markdown(md)

The markdown function should be included in the locals data when you render the jade template and can directly use a markdown library to convert the markdown syntax to HTML.



回答4:

If you are using Scalate's Jade support you can enter:

section
    :&markdown
        #{md}

You can also import external files with:

section
    :&markdown
        #{include("MyFile.md")}