In flask, to create a url I use {{ url_for('login') }}
in the template (Jinja2) and it returns whatever the url is associated the name login
(for example /auth/login/
). How do I do this in Handlebars.js and Backbone.js? Is it already implemented?
What I want to achieve:
{{#urlfor}}loginRoute{{/urlfor}}
and for that to return:
/auth/login
.
My routes:
routes: {
'': 'indexRoute',
'auth/login': 'loginRoute'
}
I cannot make sense of why you would be wanting to do this. All you would be doing is creating a Handlebars helper for finding and returning the name of a key of some Object that holds some value:
The helper would be simple enough:
Handlebars.registerHelper('urlfor', function (value) {
for (var key in routes) {
if (routes.hasOwnProperty(key) && routes[key] === value) {
return key;
}
}
return null;
});
(This assumes, of course, that the helper has access to routes
in its lexical scope.)
You would use this helper in a template in the following way:
<script id="Template" type="text/template">
<p>The URL for loginRoute is {{urlfor 'loginRoute'}}</p>
</script>
However, it seems to me that it would make more sense to forego the helper and instead do this computation before executing your template function and simply pass the value as a parameter:
template({ loginUrl: getUrlFor('loginRoute') });