How to override Handlebars' `if` helper - handlebars.js

I'm looking for a way to change how Handlebars' if helper works.
Mandrill has made a few modifications to the standard Handlebars. One of these handy changes is in the way they handle Handlebars' if block helper. They've added the ability to evaluate expressions inside the if helper like this:
{{#if `purchases > 3`}}
I need to be able to compile Mandrill templates locally, for testing and preview, and this feature is making it difficult. I know I can write my own custom helpers, but in this case I'm looking for a way to alter the way the built-in if helper works.
I guess I could build my own version of Handlebars.
Any other suggestions?

I don't think that there is a problem to redefine the standard helpers as long as yours are working fine. You'll find in the below snippet one example that override the if helper to put instead a text. So just register your own helper this will override the default one. If you want the {{else}} also working you'll have to handle it in your if helper code.
$(document).ready(function () {
var context = {
"textexample1" : "hello",
};
Handlebars.registerHelper('if', function(text) {
return new Handlebars.SafeString(text);
});
var source = $("#sourceTemplate").html();
var template = Handlebars.compile(source);
var html = template(context);
$("#resultPlaceholder").html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="sourceTemplate" type="text/x-handlebars-template">
{{#if 'test override'}}
{{textexample1}}
{{/if}}
</script>
<br/>
<div id="resultPlaceholder">
</div>

Related

Can Svelte be used for templating like Handlebars?

My objective is to let end-users build some customization in my app. Can I do something like this? I know this is sometimes also referred to as liquid templates, similar to how handlebars.js works.
app.svelte
<script>
let name = 'world';
const template = '<h1> Hello {name} </h1>'
</script>
{#html template}
I'm sorry if this is already answered, but I could not find it.
Link to REPL.
This is a little bit hacky but it will do the trick:
<script>
let name = 'world';
let template;
</script>
<div class="d-none" bind:this={template}>
<h1>Hello {name}</h1>
</div>
{#html template?.innerHTML}
<style>
.d-none {
display: none;
}
</style>
If the template should be a string one solution might be to simply replace the {variable} with the values before displaying via a {#html} element >> REPL
Notice the warning in the SVELTE docs
Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability.
(Inside a component $$props could be used to get the passed values in one object if they were handled seperately)
<script>
const props = {
greeting: 'Hello',
name: 'world'
}
let template = '<h1> {greeting} {name} </h1>'
let filledTemplate = Object.entries(props).reduce((template, [key,value]) => {
return template.replaceAll(`{${key}}`, value)
},template)
</script>
{#html filledTemplate}
Previous solution without string
To achieve this I would build a Component for every template and use a <svelte:component> element and a switch to display the selected one > REPL
[App.svelte]
<script>
import Template1 from './Template1.svelte'
import Template2 from './Template2.svelte'
let selectedTemplate = 'template1'
const stringToComponent = (str) => {
switch(str) {
case 'template1':
return Template1
case 'template2':
return Template2
}
}
</script>
<button on:click={() => selectedTemplate = 'template1'}>Template1</button>
<button on:click={() => selectedTemplate = 'template2'}>Template2</button>
<svelte:component this={stringToComponent(selectedTemplate)} adjective={'nice'}/>
[Template.svelte]
<script>
export let adjective
</script>
<hr>
<h1>This is a {adjective} template</h1>
<hr>
Well, you could do it, but that not what Svelte was designed for.
Svelte was designed to compile the template at build time.
I'd recommend using a template engine (like handlebars) for your use case.
A. Using Handlebars inside Svelte REPL:
<script>
import Handlebars from 'handlebars';
let name = 'world';
const template = "<h1> Hello {{name}} </h1>";
$: renderTemplate = Handlebars.compile(template);
</script>
{#html renderTemplate({ name })}
This of course limits the available syntax to handlebars, and you can't use svelte components inside a handlebar template.
B. Dynamic Svelte syntax templates inside a Svelte app
To be able to use svelte syntax you'll need to run the svelte compiler inside the frontend.
The output the compiler generates is not directly usable so you'll also need to run a bundler or transformer that is able to import the svelte runtime dependencies. Note that this is a separate runtime so using <svelte:component> wouldn't behave as expected, and you need to mount the component as a new svelte app.
In short, you could, but unless you're building a REPL tool you shouldn't.
C. Honourable mentions
Allow user to write markdown, this gives some flexibility (including using html) and use marked in the frontend to convert it to html.
Write the string replacements manually {#html template.replace(/\{name\}/, name)}

Controlling JS load order in Meteor with nested templates breaks with template.rendered?

I've got this template named indexmade up of a bunch of partial templates.
<template name="index">
{{> jumbotron }}
{{> crew }}
{{> projects3 }}
{{> projects2 }}
{{> faq }}
{{> contact }}
</template>
Say that I've got JS code page-transitions.js that requires the DOM of jumbotron to be fully loaded in order to run.
It's not enough to simple do:
Template.index.rendered = function(){
// load page-transitions.js
};
I HAVE to do
Template.jumbotron.rendered = function(){
// load page-transitions.js here instead
};
This can get messy really quick because you need to be VERY specific about which partial templates need which JS code. And different templates could require the same JS code so you can run into a situation where you're loading the same JS code multiple times.
Is there a way to wait until the index template has completely rendered EVERYTHING, including all nested child templates, and then run the JS code?
Meteor.startup() doesn't work in this case either.
You can try a couple of things:
First, just use the classic jQuery.ready way. because, why not?
Meteor.startup(function() {
$(document).ready(function() {
// stuff.
});
});
Or you could try Tracker.afterFlush:
Meteor.startup(function() {
// I know each Template.template.rendered has its own afterFlush, but those
// computations are defined way before Meteor.startup so then, theoretically,
// the below code should be executed last even if it triggers recomputations here.
Tracker.afterFlush(function() {
// stuff.
});
});

Meteor templates accessing subtemplate helper functions

Is it possible for a parent Meteor template to access a subtemplate directly? Ideally, I'd like to use templates a widgets with an API. I was hoping for something like this:
mypage.html
<template name="myPage">
<div class="widgetContainer"></div>
<button>submit</button>
</template>
mypage.js
Template.myPage.rendered = function(){
this.myWidgetInstance = UI.render(Template.myWidget)
UI.insert(this.myWidgetInstance, $('.widgetContainer')[0]);
}
Template.myPage.events({
'click button': function(e, template){
// I don't want this logic to live inside of mywidget.js.
// I also don't want this template to know about the <input> field directly.
var val = template.data.myWidgetInstance.getMyValue();
}
});
mywidget.html
<template name="myWidget">
<input></input>
</template>
mywidget.js
Template.myWidget.getValue = function(){
return this.$('input').val();
}
The above doesn't work because myWidgetInstance.getMyValue() doesn't exist. There doesn't appear to be a way for external code to access template helper functions on an instance.
Is anyone using Meteor templates in the way I'm trying to use them above? Or is this better suited for a separate jQuery widget? If so, it'd be a shame because I still want my widget template to benefit from the features Meteor provides.
It is possible to access subtemplate helper function.
Your example will work once you apply few fixes:
fix 1 : getValue() instead of getMyValue()
Template.myPage.events({
'click button': function(e, template){
// I don't want this logic to live inside of mywidget.js.
// I also don't want this template to know about the <input> field directly.
var val = template.myWidgetInstance.getValue();
console.log(val);
}
});
fix 2 : $('input').val(); instead this.$('input').val();
Template.myWidget.getValue = function(){
return $('input').val();
}
fix 3 : <input> should have no close tag.
<template name="myWidget">
<input type="text" value="sample value">
</template>

Pass data to a dynamic template

With meteor updates up to 0.8 my old code stopped working.
Handlebars.registerHelper('getTemplate', function(id, context) {
return Template[id](context);
});
<template name="main">
....
{{{getTemplate templateName context}}}
....
</template>
//somewhere in other template
Template.main.context = {name:value};
This way I was able to render a custom template with custom data. Now I can't find the way to pass context to the dynamic template. With blaze both templateName and context is undefined. Any advice?
Meteor >= 0.8.2
You can use the UI.dynamic helper render a template with a context which are both specified dynamically. For more details, check out this issue.
Meteor < 0.8.2
Both of these issues are addressed on this page in the meteor wiki.
Handlebars.registerHelper is now UI.registerHelper as seen here.
Examples of how to dynamically render templates are shown here.
update
Actually, given the requirements, a solution doesn't seem very obvious to me. If you are willing to use session variables to set the template name and context, AND only have one dynamic template in your main template. You could do something like this:
<body>
{{> main}}
</body>
<template name="main">
{{> getTemplate context}}
</template>
<template name="dogs">
<p>There are {{animals}} dogs!</p>
</template>
<template name="cats">
<p>There are {{animals}} cats!</p>
</template>
Session.setDefault('templateName', 'dogs');
Session.setDefault('templateContext', {animals: 10});
Template.main.getTemplate = function() {
return Template[Session.get('templateName')];
};
Template.main.context = function() {
return Session.get('templateContext');
};
This was brought up on the meteor-core list and #dgreensp, MDG core dev working on Blaze, opened Ticket #2007 - How to render a template to HTML with data so they definitely know about this and I'd expect a fix to land soon after 0.8.0.
He also included the following workaround:
var toHTMLWithData = function (kind, data) {
return UI.toHTML(kind.extend({data: function () { return data; }}));
};
The github ticket has further discussion and alternate code snippets that you may find useful.

HandlebarsJS not outputting html template unless receives a param

I have this code:
if (this.template) {
var template = Handlebars.compile( $(this.template).html() );
$(this.el).html(template());
}
with this template:
<script id="tmpl-nav-account" type="text/x-handlebars-template">
{{#this}}
<div class="nav-account">
topbar
</div>
{{/this}}
However, if run the 'template()' function with no params, nothing outputs. Yet, if I pass something in like: "template('ben')", it outputs the static HTML fine. Anyone got any ideas?
Does template() always have to have something passed into it to render the template?
EDIT:
If I remove the {{#this}} from the template, then it works with no parameters...
The this at the top level of a template is the argument you supply to the compiled template function. So, given this:
var o = { ... };
var t = Handlebars.compile(some_template_text);
t(o);
this will be o at the top level of the template. So, if you say template(), this is undefined inside the template and {{#this}} won't do anything because undefined is false in a boolean context.
You can see this clearly if you use this template:
<script id="tmpl-nav-account" type="text/x-handlebars-template">
{{#this}}
<div class="nav-account">
{{this.where_is}}
</div>
{{/this}}
</script>​
and this JavaScript:
var t = Handlebars.compile($('#tmpl-nav-account').html());
console.log(t());
console.log(t({ where_is: 'pancakes house?' }));​
Demo: http://jsfiddle.net/ambiguous/fS8c9/

Resources