helpers / handlebars-helpers

188 handlebars helpers in ~20 categories. Can be used with Assemble, Ghost, YUI, express.js etc.
http://assemble.io/helpers/
MIT License
2.22k stars 364 forks source link

How to pass options to Markdown #321

Closed sidonaldson closed 6 years ago

sidonaldson commented 6 years ago

Is it possible to pass options to Remarkable via the Markdown helper?

doowb commented 6 years ago

Yes, something like this should work:

{{#markdown linkify=true}}
https://github.com/helpers/handlebars-helpers
{{/markdown}}
sidonaldson commented 6 years ago

I was hoping there might be a way to extend Remarkable to create custom renderers. In the end I created a new Remarkable instance and added a markdown2 helper.

Just in case anyone else needs the code

// custom image renderer
const escapeHtml = require('../node_modules/remarkable/lib/common/utils').escapeHtml;
const replaceEntities = require('../node_modules/remarkable/lib/common/utils').replaceEntities;
const unescapeMd = require('../node_modules/remarkable/lib/common/utils').unescapeMd;

module.exports = (md) => {
    md.renderer.rules.image = function(tokens, idx, options) {
        let src =  escapeHtml(tokens[idx].src);
        let title = tokens[idx].title ? (' title="' + escapeHtml(replaceEntities(tokens[idx].title)) + '"') : '';
        let alt = ' alt="' + (tokens[idx].alt ? escapeHtml(replaceEntities(unescapeMd(tokens[idx].alt))) : '') + '"';
        let suffix = options.xhtmlOut ? ' /' : '';
        return `
            <div class="loading">
                <div class="image-holder">
                    <img src="/images/pixel.png" data-src="${src}" ${alt} ${title} ${suffix} class="lazy lazy--loading"/>
                </div>
            </div>`;
    };
    return md;
};
// import helpers
const hbshelpers = require('handlebars-helpers')();
const Remarkable = require('remarkable');
const md = new Remarkable({html: true, breaks: true});
const customImg = require('./remarkable-image');
md.use(customImg);

module.exports = (app) => {

    let helpers = hbshelpers;

    helpers.markdown2 = (str) => {
        return md.render(str);
    };
};
//  app
var hbs = exphbs.create({
    extname: 'hbs',
    layoutsDir: 'app/views/layouts',
    defaultLayout: 'main',
    helpers: require('./lib/handlebar-helpers')(app),
    partialsDir: [
        'app/views/partials'
    ]
});