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

时间:2011-01-17 20:44:20

标签: node.js block pug

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

元素的网页。

例如,要创建这样一个段落,我相信我需要这样做:

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

对于一个充满真实文本段落的静态网页,由于每行开头的管道符号,使用玉石会成为负担。

是否存在某种语法糖用于将整个块标记为文本节点,因为管道符号逐行进行?或者我不知道的现有过滤器?

我正在探索的一个解决方案是创建一个:块过滤器或其他东西,它在每行前面加上|然后将它传递给Jade,但是jade关于创建过滤器的文档至少可以说是稀疏的,所以可能需要一段时间来弄明白。如果有人能就这样的解决方案提供指导,我会很感激。

2 个答案:

答案 0 :(得分:39)

来自jade github page

p.
foo asdf
asdf
 asdfasdfaf
 asdf
asd.

产生输出:

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

p之后的跟踪期是您正在寻找的。

答案 1 :(得分:8)

经过一些修补,我找到了完成此操作的过滤器的详细信息。在这里发布答案,因为我想这对使用玉的其他人有用。

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

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);
};

然后标记看起来像这样。请注意,它允许您在其间包含其他玉石:文本块:

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