How do I pass content from a template to a layout in Express?

后端 未结 6 1594
忘了有多久
忘了有多久 2021-01-31 00:25

I have a basic Express server:

// server.js:
var Express = require(\'express\');
app = Express.createServer();
app.configure(function(){
  app.set(\'views\', Pat         


        
6条回答
  •  无人及你
    2021-01-31 01:05

    Using the tip above about dynamicHelpers, and the magic of closures, I found a fairly elegant solution that works without involving the request object. The trick is to wrap the page title variable in a closure that provides a get() and set() function around it, and make that wrapper object the result of the page_title dynamic helper.

    Create a property.js:

    exports.create = function () {
        var value = null;
        return {
            get: function () {
               return value;
            },
            set: function (new_value) {
               value = new_value;
            }
        };
    }
    

    So calling create() returns an object with a get() and set() method on it, that get and set the closure variable.

    Then, in your app's setup code:

        var property = require("./property.js");
        app.dynamicHelpers ({
            page_title: function () {
             return property.create ();
            }
        });
    

    Since the dynamic helper's value is the result of calling its function, in your view and template, the page_title variable will be the wrapper object with the get() and set() functions.

    In your view, you can then say:

    - page_title.set ("my specific page title");
    

    And in your layout:

    title= page_title.get()
    

    To simplify this a bit further, adding this to property.js:

    exports.creator = function () {
        return function () {
            return exports.create();
        };
    }
    

    Lets you simplify the dynamic helpers declaration block to this:

            var property = require("./property.js");
            app.dynamicHelpers ({
                page_title: property.creator()
            });
    

提交回复
热议问题