categories loop on a plugin
-
whats the best approach to list categories from my forum with a plugin?
thank you
-
If you just want the list, you can do something like
Categories.getAllCategoryFields(['name', 'parentCid', 'children'], function(err, categories) { console.dir(categories); });
If you want to display them in a template, I would copy what's in the categories controller. It gets all the categories by privilege, then puts them in a tree format, for easy display.
https://github.com/NodeBB/NodeBB/blob/master/src/controllers/categories.js#L43-L51
-
@yariplus said in categories loop on a plugin:
If you just want the list, you can do something like
Categories.getAllCategoryFields(['name', 'parentCid', 'children'], function(err, categories) { console.dir(categories); });
If you want to display them in a template, I would copy what's in the categories controller. It gets all the categories by privilege, then puts them in a tree format, for easy display.
https://github.com/NodeBB/NodeBB/blob/master/src/controllers/categories.js#L43-L51
so included script on my tpl and...
Uncaught Error: Module name "../categories" has not been loaded yet for context: _. Use require([])
-
@yariplus said in categories loop on a plugin:
@exodo Those are for the server, on the client use socket.io
socket.emit('categories.get', {}, function(err, data){ console.dir(data); /* data is an array of categories. */ });
i see thank you
can you explain how to make it with the server and how to call it on the template? -
Sure.
library.js
Plugin = module.exports; var categories = require.main.require('./src/categories'); // init hook Plugin.init = function (data, callback) { var router = data.router; var middleware = data.middleware; // Create route to render the template to. router.get('/example-categories', middleware.buildHeader, renderExampleCategories); router.get('/api/example-categories', renderExampleCategories); function renderExampleCategories(req, res, next) { // Get all the visible categories. categories.getCategoriesByPrivilege('cid:0:children', req.uid, 'find', function(err, categoryData) { if (err) return next(err); // Put the categories in a tree format. categories.flattenCategories([], categoryData); // Send the data to the template. `example-categories.tpl` res.render('example-categories', {categories: categoryData}); }); } };
example-categories.tpl
<!-- BEGIN categories --> <a href="{config.relative_path}/category/{categories.slug}" itemprop="url">{categories.name}</a> <br> <!-- BEGIN categories.children --> - <a href="{config.relative_path}/category/{categories.children.slug}" itemprop="url">{categories.children.name}</a> <br> <!-- END categories.children --> <!-- END categories -->
Should give you a list like this