Vladimir Starkov
Vladimir Starkov

Reputation: 19803

Using locales options inside the jade filter failed

I'm trying to use locales option inside the filter but faced with problem, that locale-object is not accessible from filter.

Locales: json {"title": "HAMPI"}

Filter:

var jade = require(jade);
jade.filters.Posts = function(block) {
    return '{block:Posts}'+jade.render(block)+'{/block:Posts}';
};

Input:

body
    |#{title}
    :Posts
        div
            a
                #{title}

Output:

<body>
    HAMPI
    {block:Posts}<div><a><undefined></undefined></a></div>{/block:Posts}
</body>

Can I fix or handle this error?

PS You can look at the code in this repository — I'm using grunt and grunt-contrib-jade plugin, but to force grunt-contrib-jade work with filters you should edit ./node_modules/grunt-contrib-jade/tasks/jade.js to reflect changes from this pull request.

Upvotes: 0

Views: 569

Answers (1)

user568109
user568109

Reputation: 48003

Filters are applied at compile time, where as rendering which has access to local variables is done at runtime. So your local variables are not accessible to filters. They only see raw text. So you can do this :

jade.filters.Posts = function(block) {
    return '{block:Posts}'+block+'{/block:Posts}'; //remove render
};

This way you will defer rendering of #{title} until you have the variables. It produces this output.

<body>HAMPI{block:Posts}HAMPI{/block:Posts}</body>

How I tested it :

var jade = require(jade);
fn = function(block) {
    return '{block:Posts}'+jade.render(block)+'{/block:Posts}';
};
var fn = jade.compile(fs.readFileSync(__dirname + '/file2.jade'));
console.log(fn({"title": "HAMPI"}));

The same issue is mentioned in here: in node.js, how to pass variables to :stylus filter from jade?

For reference you can see these links :

[Update]

If you want to use render then why not pass the local vars with it. So if you do :

jade.filters.Posts = function(block) {
    return '{block:Posts}'+jade.render(block,{"title": "HAMPI"})+'{/block:Posts}'
};

It gives this:

<body>HAMPI{block:Posts}<div><a><HAMPI></HAMPI></a></div>{/block:Posts}</body>

Downside being your view local cannot be used and you would have to pass it directly.

Upvotes: 1

Related Questions