Create custom route in plugin



  • Hey Guys, is there anyway to make custom route in plugin? I saw there are navigation tab and home page tab that could add and config new route as plugin, but how could I config the content of the route?

    Is there any example to follow?

    Thanks!


  • Community Rep

    You define routes in your load hook. So your library.js might look like this:

    var Plugin = module.exports = {};
    Plugin.load = function (params, callback) {
    
    	var router = params.router;
    	var middleware = params.middleware;
    
    	// Define the function that renders the custom route.
    	function render(req, res, next) {
    
    		// Get whatever data you want to send to the template here.
    		var data = {whatever: 33};
    
    		// This is the path to your template without the .tpl, relative to the templates directory in plugin.json
    		var template = 'templatename'
    
    		// Send the page to the user.
    		res.render(template, data);
    	}
    
    	// This actually creates the routes, you need two routes for every page.
    	// The first parameter is the actual path to your page.
    	router.get('/yourpage', middleware.buildHeader, render);
    	router.get('/api/yourpage', render);
    
    	callback();
    };
    

    And your plugin.json would look something like this:

    {
    	"library": "library.js",
    	"hooks": [
    		{ "hook": "static:app.load", "method": "load" }
    	],
    	"templates": "./public/templates",
    	"staticDirs": {
    		"public": "public"
    	}
    }
    

    and you would have a template here:
    /nodebb-plugin-yourplugin/public/templates/templatename.tpl

    <h2>My Awesome Custom Page</h2>
    The Magic Number is: {whatever}
    

    I'm pretty sure I posted about this before, with more details even. Have to start using those canned responses. :rose:


Log in to reply
 

Looks like your connection to NodeBB was lost, please wait while we try to reconnect.