NodeBB-Community / nodebb-plugin-custom-pages

Allows you to add as many new pages as you like to your NodeBB forum
BSD 2-Clause "Simplified" License
39 stars 24 forks source link

Pass more data to rendered custom pages #37

Closed reliasn closed 7 years ago

reliasn commented 8 years ago

The idea is to allow us to create custom pages with the user's info:

<!-- IF config.loggedIn -->
<div>
    Hello {user.email}
</div>
<!-- ELSE -->
<div class="alert alert-warning" style="text-align: center">
    Register first.
</div>
<!-- ENDIF config.loggedIn -->

I'm struggling a little to figure out how data is being passed when you call res.render, but anyways, the above fails because {user} isn't available, while {config} is. So the workaround that I managed to implement was this one:

<!-- IF config.loggedIn -->
<div id="custom_div">
</div>
<script>
    document.getElementById('custom_div').innerHTML = 'Hello ' + app.user.email;
</script>
<!-- ELSE -->
<div class="alert alert-warning" style="text-align: center">
    Register first.
</div>
<!-- ENDIF config.loggedIn -->

This seems to work because header.tpl has this:

<script>
    var RELATIVE_PATH = "{relative_path}";
    var config = JSON.parse('{{configJSON}}');
    var app = {
        template: "{template.name}",
        user: JSON.parse('{{userJSON}}')
    };
</script>

which adds the user info to the app variable.

Is this workaround the only solution considering how this plugin is implemented or am I missing something?

reliasn commented 8 years ago

I ended up writing a plugin that creates another route and renders my template with the user data:

"use strict";

var plugin = {},
    db = module.parent.require('./database');;

plugin.init = function(params, callback) {
    var app = params.router,
        middleware = params.middleware,
        controllers = params.controllers,
        helpers = module.parent.require('./routes/helpers');

    var Forum = db.client.collection('objects');

    helpers.setupPageRoute(app, '/subscribe', middleware, [], function(req, res, next){
        Forum.findOne({_key: req.uid}, function(err, data){
            res.render('subscribe.tpl', {user: data})
        })
    });

    callback();
};

module.exports = plugin;

I suppose nodebb-plugin-custom-pages was made for static pages, but it would be great if it could have some extra features that could turn the content more dynamic.