Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use in expressjs? #8

Open
rafis opened this issue Jul 13, 2016 · 3 comments
Open

How to use in expressjs? #8

rafis opened this issue Jul 13, 2016 · 3 comments

Comments

@rafis
Copy link

rafis commented Jul 13, 2016

How to use in expressjs? I have type "expressjs pithy" in google - no results.

@derhuerst
Copy link

I can show you my web app as an example.

The /departures route requires the departures template`, which just exports a function, that takes data and returns an HTML string.

Probably not the easiest example, but I hope it helps you.

@rafis
Copy link
Author

rafis commented Jul 18, 2016

I mean Express 'view engine'. Something like this:

exports.__express = function(path, options, callback) {
    var html;
    try {
        var template = require(path);
        html = template.call(options).toString();
    } catch(e) {
        callback(e);
        return;
    }
    callback(null, html);
};

And views/index.pithy:

var html = require('pithy');
module.exports = function() {
    return html.html(null, [
        html.head(null, [
            html.title(null, this.title)
        ]),
        html.body(null, this.text)
    ]);
};

Usage in route action:

function(req, res, next) {
    res.render('views/index.pithy', { title: 'Title', text: 'Hello, World!' });
}

@derhuerst
Copy link

I mean Express 'view engine'.

As the documentation says, those template engines are just a function taking 3 arguments:

  • the template name/file,
  • an object filled with data to be used by the template,
  • a callback to be called with the rendered HTML.

Something like this might work with pithy:

const p = require('pithy')

const templates = {
    // minimal working example
    main: (data) => p.html(null, [
        p.body(null, [
            p.h1(null, data.title),
            p.p(null, data.message)
        ])
    ])
    // …
}

app.engine('unicorn', (template, data, cb) => {
    if (!(template in templates))
        return cb(new Error('unknwon template'))
    return cb(null, templates[template](data))
})

app.set('view engine', 'unicorn')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants