Blaze js => Pass spacebars in JS

Hi there,

Simple question, is it possible to pass spacebars into javascript, that would be interpreted in html by Blaze ?

Something like this (In a pagination helper) :

if (pagesNumber > 1) {
            displayPages = '<li class="page-item"><a class="page-link" href="{{pathFor "partners/page" page='+(Template.instance().page.get() - 1)+'}}">Previous</a></li>';
            for (let index = 0; index < pagesNumber; index++) {
                displayPages += '<li class="page-item"><a class="page-link" href="{{pathFor "partners/page" page='+index+'}}">'+index+'</a></li>';
            };
            displayPages += '<li class="page-item"><a class="page-link" href="{{pathFor "partners/page" page='+(Template.instance().page.get() + 1)+'}}">Previous</a></li>';
        }
        return displayPages;

Thanks a lot for answers,

Happy coding anyway,

B.

Hi brawcks, yes it is possible to pass it to blaze. The only thing that you need to do is call the helper in the html template like this: {{{helpername}}}.

1 Like

Hi Juan,

Nice, i’ve tried it it worked, so i rendered the HTML in my template. There is only one thing which didn’t worked, it’s the spacebar i put into the helper : {{pathFor “partners/page” page=’+index+’}}

It’s rendered “as is”, so this part isn’t interpreted by blaze.

Any idea ?

Thanks :slight_smile:

This part wont actually be rendered through the curly braces, what I would do in this case is add a special class to the page-preview and page-next and just do a click event that runs the Template.instance().page.get() ± 1 with the Flowrouter.go or if you are using iron:router its equivalent.

I’m pretty sure this won’t work at all. The spacebars templates are compiled into JS files during build, so the client never even sees the curly braces.

Instead you should just evaluate the result yourself using FlowRouter.path, or your router’s equivalent:

if (pagesNumber > 1) {
    const pageNum = Template.instance().page.get();
    const prevPath = FlowRouter.path("partners/page", { page: pageNum - 1 })
    displayPages = '<li class="page-item"><a class="page-link" href="'+prevPath+'">Previous</a></li>';
    for (let index = 0; index < pagesNumber; index++) {
        const iPath = FlowRouter.path("partners/page", { page: index })
        displayPages += '<li class="page-item"><a class="page-link" href="'+iPath+'">'+index+'</a></li>';
    };
    const nextPath = FlowRouter.path("partners/page", { page: pageNum - 1 })
    displayPages += '<li class="page-item"><a class="page-link" href="'+nextPath+'">Previous</a></li>';
}
return displayPages;

Or even better, you should be able to specify this in the original template. Can you post your template code?

Okay ! I see :slight_smile:

You solved my problem, thanks a lot for your help ! I didn’t know the flowrouter.path function.

Looks great !

Happy coding and thanks again :slight_smile:

1 Like