Search code examples
templatespuglocals

Pug/Jade get all variables in a given template


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.


Solution

  • This is not a full answer to your problem but more of a starting point. From debugging the pug code, i have noticed you could probably "hook" a plugin in one of the steps of template "compilation" to code. Look here. It seems that in the various steps of compilation, you can access the diffrent nodes present in the template.

    You could also look at this, it seems to offer almost what you are looking for.

    If you do something like

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

    The contents of tokens is an array of the diffrent tokens, the one that are of type "code" or "interpolate-code" seem to be the diffrent variables.

    Hope this helps