Jade模板引擎(在Node.js下):没有管道符的多行块

16

我目前正在一个新项目上使用Jade。它似乎非常适合构建Web应用程序的布局,但不适合编写静态内容,例如包含文本

元素的网页。

例如,为了创建这样的段落,我认为需要这样做:

p
  | This is my long,
  | multi-line
  | paragraph.

对于一个充满真实段落文本的静态网页来说,使用Jade因为每行开头都有管道符号而变得繁琐。

有没有一种语法糖可以将整个块标记为文本节点,就像管道符号逐行处理一样?或者我不知道的已有过滤器吗?

我正在探索的一个解决方案是创建一个:block过滤器或其他东西,将每一行加上|然后传递给Jade,但是Jade关于创建过滤器的文档非常有限,所以可能需要一段时间才能弄清楚。如果有人能够提供这样的解决方案的指导,我将不胜感激。

2个回答

39

来自jade的GitHub页面:

p.
foo asdf
asdf
 asdfasdfaf
 asdf
asd.

产生输出:

<p>foo asdf
asdf
  asdfasdfaf
  asdf
asd
.
</p>

你要找的是 p 后面的句点。


1
必须赞扬原帖作者在解决方案中所做的所有工作,考虑到原帖作者只需要添加一个句号。 - timoxley
我认为当我发布问题时,该功能不存在,或者至少没有记录。好知道-谢谢。 - Jake

8

经过一些调试,我终于想出了一个实现这个功能的过滤器。我在这里发布答案,因为我认为这对使用jade的其他人也会有所帮助。

创建过滤器的代码非常简单:

var jade = require ("jade");

jade.filters.text = function(block, compiler){
    return new TextBlockFilter(block).compile();
};

function TextBlockFilter(node) {
    this.node = node;
}

TextBlockFilter.prototype.__proto__ = jade.Compiler.prototype;

TextBlockFilter.prototype.visit = function(node){

    // first this is called with a node containing all the block's lines
    // as sub-nodes, with their first word interpreted as the node's name
    //
    // so here, collect all the nodes' text (including its name)
    // into a single Text node, and then visit that instead.
    // the child nodes won't be visited - we're cutting them out of the
    // parse tree

    var text = new jade.nodes.Text();
    for (var i=0; i < node.length; i++) {
        text.push (node[i].name + (node[i].text ? node[i].text[0] : ""));
    }
    this.visitNode (text);
};

然后标记看起来像这样。请注意,它允许您在:text块之间包含其他jade内容:

p
  :text
    This is my first line of text,
    followed by another
    and another.  Now let's include a jade link tag:
  a(href="http://blahblah.com")
  :text
    and follow it with even more text 
    and more,
    etc

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