bsr
bsr

Reputation: 58662

Getting access to data in jade template (to make static html)

I am trying to pass some data to jade template to generate static content. I do not know much about node.js and express, I don't use them as backend. I use jade as a template engine and to generate static html.

There are lot of request in jade issue list about having multi line code, and the owner comments

I'd like to promote keeping too much js out of the templates, maps etc can be exposed via locals

if there's a lot of logic or objects etc within a template you should be using app.helpers() etc, they can still be view-only helpers but at least it keeps the templates cleaner

I am not quite sure how to do this in a grunt based environment. Basically, if I can get access to javascript variables (which may be a text, js or json file) in my jade template, so I can use the data in my template and generate static html files. What is the best way to do this?


Edit

To clarify further, I may have data like (say in a json file)

user1 = {link: '', lbl: 'User', txt: '.... lot 0f text ....'}
user2 = {link: '', lbl: 'User', txt: '.... lot 0f text ....'}

in my mixin, somehow I need to access user1, user2 etc in my jade template

.content
        +colum(user1 )
        +colum(user2 )

mixin colum(d)
    .span4
        h4
            | #{d.lbl}
        p
            | #{d.txt}

Thanks a ton.

Upvotes: 4

Views: 5580

Answers (3)

Kyle Robinson Young
Kyle Robinson Young

Reputation: 13762

If you want to do it with grunt-contrib-jade try the data option:

jade: {
  compile: {
    options: {
      data: function(dest, src) {
        // Return an object of data to pass to templates
        return require('./userData.json');
      },
    },
    files: {
      "dest.html": ["templates/*.jade"]
    },
  },
}

Here are the docs on it: https://github.com/gruntjs/grunt-contrib-jade#data

Upvotes: 5

Rikky
Rikky

Reputation: 515

Hope this helps: The jade public API https://github.com/visionmedia/jade#readme

Update: after play around for awhile, I got this:

var jade = require('jade');

// Compile a function
var fn = jade.compile('p= data');
console.log(fn({'data':'test'}));

When I ran this code, I got: <p>test</p>. So here is how jade can work:

jade.complie(jadeString) is a function to determine what string that jade have to complie - the jadeString parameter, you can use fs module to load the content of your jade template and place it here. fn(jsonData) is the function that actually complie the jade template to html, jsonData is the data you want to use in the template.

Upvotes: 1

Rikky
Rikky

Reputation: 515

You can render your data in jade with: #{your_variable}

Upvotes: 1

Related Questions