Как использовать регистрационные помощники для node.js и экспресс-рулей - PullRequest
0 голосов
/ 28 ноября 2018

У меня есть опция выбора в моей форме, и после загрузки записи я хочу выбрать сохраненную опцию.Вот код:

Файл Student.hbs, в котором я отображаю форму, объект obj исходит от маршрута student.js

student.hbs

<form>
    <div class="form-group">
        <label for="day">Day</label>
        <select name="day" id="day" class="form-control">
            <option value="monday" {{{select act.day 'monday'}}}>Monday</option>
            <option value="tuesday" {{{select act.day 'tuesday'}}}>Tuesday</option>
            <option value="wednesday" {{{select act.day 'wednesday'}}}>Wednesday</option>
            <option value="thursday" {{{select act.day 'thursday'}}}>Thursday</option>
            <option value="friday" {{{select act.day 'friday'}}}>Friday</option>
            <option value="saturday" {{{select act.day 'saturday'}}}>Saturday</option>
            <option value="sunday" {{{select act.day 'sunday'}}}>Sunday</option>
        </select>
    </div>
</form>

student.js

router.get('/view/:actUUID', (req, res) => {
    var uuid = req.params.actUUID;
    Student.findByPk(uuid).then(act => {
        res.render('student', {
            act: act 
        });
    });
});

Я создал помощник руля в /handlers/handlebars.js, где я пишу все свои вспомогательные функции.

app.js

var exphbs = require('express-handlebars');
var hbsHelpers = exphbs.create({
    helpers:require('./handlers/handlebars').helpers, 
    defaultLayout: 'main', 
    extname:'.hbs'
});

app.engine('.hbs', hbsHelpers.engine);
app.set('views', path.join(__dirname, 'views'));                 
app.set('view engine', 'hbs');

/ handlers / handlebars.js

function hbsHelpers(hbs) {
    return hbs.create({
        helpers: {
            select: function (selected, option) {
                return (selected == option) ? 'selected="selected"' : '';
            }
        }
    });
}
module.exports = hbsHelpers;

Но когда я перехожу на страницу студента, яполучить следующую ошибку

Ошибка: отсутствует помощник: «выбрать» в объекте.(/ Volumes / Macintosh HD 2 / GitHub, клонированный Repos / action-tours / node_modules / handlebars / dist / cjs / handlebars / helpers / helper-missing.js: 19: 13) в Object.eval [как основной] (eval в createFunctionContext)(/ Volumes / Macintosh HD 2 / Клонированные репозитории GitHub / action-tours / node_modules / handlebars / dist / cjs / handlebars / compiler / javascript-compiler.js: 254: 23),: 15: 74) в основном (/ Volumes /Macintosh HD 2 / клонированные репозитории GitHub / action-tours / node_modules / handlebars / dist / cjs / handlebars / runtime.js: 175: 32) в отставке (/ Volumes / Macintosh HD 2 / клонированные репозитории GitHub / action-tours / node_modules /handlebars / dist / cjs / handlebars / runtime.js: 178: 12) в режиме ret (/ Volumes / Macintosh HD 2 / GitHub, клонированный Repos / action-tours / node_modules / handlebars / dist / cjs / handlebars / compiler / compiler.js:526: 21) в ExpressHandlebars._renderTemplate (/ Volumes / Macintosh HD 2 / GitHub, клонированный Repos / action-tours / node_modules / express-handlebars / lib / express-handlebars.js: 247: 12) в ExpressHandlebars.(/ Тома / Macintosh HD 2 / Клонированные репозитории GitHub / action-tours / node_modules / express-handlebars / lib / express-handlebars.js: 173: 21)

Ответы [ 2 ]

0 голосов
/ 01 мая 2019

В /handlers/handlebars.js

вы делаете что-то вроде этого

module.exports = {
      select: function(selected, options){
            return options.fn(this).replace( new RegExp(' value=\"' + selected + '\"'), '$& selected="selected"').replace( new RegExp('>' + selected + '</option>'), ' selected="selected"$&');
        },
};
0 голосов
/ 02 декабря 2018

Так что, похоже, нет необходимости возвращать hbs.create в файл handlebars.js.

Правильный способ сделать это будет:

app.js

var exphbs = require('express-handlebars’);
.
.
.

var hbs = exphbs.create({
    helpers: require('./handlers/handlebars'),
    defaultLayout: 'main',
    extname:'.hbs'
});

.
.
app.engine('.hbs', hbs.engine);

В /handlers/handlebars.js

module.exports = {
    select: function (selected, option) {
        return (selected == option) ? 'selected="selected"' : '';
    }
};
...