5

For a given Jade/Pug template I would like to get a list of all variables which occur within the template.

My motivation is as follows: In my software, different templates are used to generate some HTML snippets. Based on a given context (i.e. values for certain variables are given), I would like to suggest only those templates, where all variables within the template can be assigned.

Example: For template myTemplate like this:

html
    head
        title= myTitle
    body
        h1 #{value.headline}
        p #{paragraph.text}

I would like to get some output like this:

var variableNames = extractVariableNamesFromTemplate('myTemplate');
// variableNames = [ 'myTitle', 'value.headline', 'paragraph.text' ]

Is there something available ready-to-use? Preferably a solution which would take into account all language-specific features such as includes, extends, etc.

4

1 回答 1

2

这不是您问题的完整答案,而是更多的起点。通过调试 pug 代码,我注意到您可能会在模板“编译”到代码的步骤之一中“挂钩”一个插件。看这里。似乎在编译的各个步骤中,您可以访问模板中存在的不同节点。

你也可以看看这个,它似乎提供了几乎你正在寻找的东西。

如果你做类似的事情

var lex = require('pug-lexer');

var filename = 'template.pug';
var src = `
html
    head
        title= myTitle
    body
        h1 #{value.headline}
        p #{paragraph.text}`;

var tokens = lex(src, {filename});

标记的内容是不同标记的数组,“代码”或“插值代码”类型的标记似乎是不同的变量。

希望这可以帮助

于 2016-11-24T03:21:32.743 回答