how to create and use a template helper
-
Building a custom theme based on vanilla:
I want to show theposts.index
for each post in the topic.tpl template
The problem is that the first post is, obviously, #0, and I want it to display #1. Also the href should be/1
, and not/0
Well, as far as I know, you can't just do
{posts.index+1}
, you need a template helper. How should a theme register and use a custom template helper? Should I editpublic/src/helpers.js
manually???I can't find an example, hope you guys can help.
Thanks in advance, and great job with nodebb, it is clearly a next-generation forum platform. -
Hi
First you need to add some plugin-like functionality to your theme
Next you have to add hook for static:app.load
You have to require templates.jsvar templates = module.parent.require('templates.js');
And last thing you have to do inside of static:app.load hook
templates.registerHelper('superCoolHelper', function(data) { // here your code });
-
thank you @Oleksandr-Pidlisnyi
I've modified ourplugin.json
to add a hook:{ "hook": "static:app.load", "method": "appLoad" }
then added that
appLoad
method in our theme lib js:Theme.appLoad = function(params, callback) { templates.registerHelper('postIndexPlusOne', function(data) { return data.index+1; }); callback(); };
this way, instead of using
posts.index
(there is a bug here, try to add{}
and see what happens) in topic.tpl now we can use{function.postIndexPlusOne}
again, thank you!
-
not so fast
the function works, and prints post indexes starting at #1 instead of #0 BUT, there is a problem, a big one:
it only works if you load the topic from scratch, I mean, if you navigate from topic list to topic then it doesn`t work, and shows:#{function.postIndexPlusOne}
if you press F5, then it works again:
#1 #2 ...
is that a bug or a feature? the template is the same, but it just works on page load, not on ajax loaded content.
should I open an issue?
-
@TheBronx all you have to do is run the same code on DOM ready for it to work on client side. Add this to your client-side JS:
$(document).ready(function() { templates.registerHelper('postIndexPlusOne', function(data) { return data.index+1; }); });
EDIT: this is how you add client-side JS files from your plugin.json:
https://github.com/NodeBB/nodebb-plugin-quickstart/blob/master/plugin.json#L21-L23
-
@psychobunny understood. now we understand a lot of things regarding templates. thank you too!
-
Use 'Benchpress' import instead of 'templates' in latest version(s).
library.js var Benchpress = module.parent.require('benchpressjs'); var library = {}; library.init = function (params, callback) { Benchpress.registerHelper('someFunc', function (arg1) { return arg1*2; }); callback(); };
-
@mrazadar using
require.main.require
is what I recommend for plugins and themes -
Does it still work? My helper functions don't seem to be recognize in my template files.