On 9 May 2012 17:37, rkjha <
rkjha...@gmail.com> wrote:
> To render category in sidebar view, I want to use dynamic helper and
> in the function I want to call a model to fetch categories from db.
You can't use callbacks in the dynamic helpers - the return value of
the function is what is used, the callbacks will run but their output
is ignored.
You'll have to load the categories before rendering the templates -
route middleware is useful for this - you'd have something like
(adapting your example):
function loadCategories (req,res,next) {
category.cat_by_id(null,function(cats,err){
if(!err){
res.local('cats', cats);
next();
return cats;
}
else{
res.local('cats', cats);
next(null); // to continue processing
// next(err); // to abort processing
}
}
}
You'd then use this route middleware before calling any page that
needs a sidebar
app.get('/has/a/sidebar', loadCategories, function (req,res) { ... });
see
http://expressjs.com/guide.html#route-middleware for more details
PS: If you are happy to abort processing the request on an error then
the code can be shortened to:
function loadCategories (req,res,next) {
category.cat_by_id(null,function(cats,err){
res.local('cats', cats);
next(err); // if err is true will abort, otherwise continue
}
}
NOTE: in cat_by_id you have (cats,err) but convention would be to do (err,cats)
Cheers,
Edmund
> dynamicHelper code :
> categories:function(){
> category.cat_by_id(null,function(cats,err){
> if(!err){
> console.log(cats);
> return cats;
> }
> else{
> return null;
> }
> });
> },
>
> view code :
> <ul class="nav nav-list">
> <% for(var index in categories){ %>
> <li class="nav-header"><a href="/blog/cat/<%=
> categories[index].id %>"></a><%= categories[index].cat_name%></li>
> <% } %>
> </ul>
> But I cant found the result on view.
> Plz help me.
>
> --
> You received this message because you are subscribed to the Google Groups "Express" group.
> To post to this group, send email to
expre...@googlegroups.com.
> To unsubscribe from this group, send email to
express-js+...@googlegroups.com.
> For more options, visit this group at
http://groups.google.com/group/express-js?hl=en.
>