rendering some dynamic blocks on page - express.js + jade - node.js

Looking for a solution for a few days. Need help.
Source:
node.js + express.js + jade template engine
Problem:
Can't understand how I can render 1+ dynamic blocks on one page.
For example:
We have a page: News main page
Blocks on page: Latest news (list 20 itens), hot news (list 4 items), most viewed news (4 items), block with news categories (it can display current category on the page with page with card of one selected novelty, so it is dynamic block too), and block with some user auth data.
"block" i mean a widget as we can see on site, not a block of code.
What can I do in express? I can route special url to special function in routes.
So as I see, if a want to render all this blocks on the one page I have to call all functions rendering each block in only one function of route.
I mean it seems that I have to do something like this (sure in libs but doesn't matter here)
app.get('/news', function(req, res){
call_last_news(funcion(){
call_hot_news(function(){
call_get_user_info(function(){
...
...
...
template.render.here();
final_here();
});
});
});
});
This looks real but so unuseful and unsupportable code that .. That's bad.
I can see solution in calls from template engine to render some blocks on the page. But not just include because all blocks can use db or cookies, session data etc. all blocks are dynamic. But I have no idea how to create such engine using express.js + jade

Well I'm not certain I understood all of the problem but based on the pseudo code, it looks like the main concern here is that you have a deeply nested set of potentially independent and reusable functions. There are two approaches to this problem that come to mind:
Use a control flow library
Use something like async series, parallel, etc. (which function depends on the nature of your code – are all of the call_ functions independent?) That will clean up your code and make it more maintainable.
Use ajax
Another approach you can take is to quickly render the page without all of the call_ functions and just make several ajax calls from the client to fill in the data. You could have routes which look like '/news/last', and '/news/hot', etc. This is nice because you can separate out all of the logic for each of these units into reusable URLs so you can mix and match them on any page.

Related

Reusing Yesod widgets in AJAX results

I'm writing a very simple Yesod message list that uses AJAX to add new list items without reloading the page (both in the case of other users modifying the database, or the client themselves adding an item). This means I have to encode the HTML structure of the message items in both the Halmet template (when the page loads initially) and the Julius template (for when the dynamic addition happens). They look something like this:
In homepage.hamlet:
$if not $ null messages
<ul id=#{listId}>
$forall Entity mid message <- messages
<li id=#{toPathPiece mid}>
<p>#{showMarkdown $ messageText message}
<abbr .timeago title=#{showUTCTime $ messagePosted message}>
And in homepage.julius:
function(message) {
$('##{rawJS listId}').prepend(
$('<li>')
.attr('id', message.id)
.append('<p>' + message.text + '</p>')
.append($('<abbr class=timeago />')
.attr('title', message.posted).timeago())
.slideDown('slow')
);
}
I'd love to be able to unify these two representations somehow. Am I out of luck, or could I somehow abuse widgets into both generating an HTML response, and filling in code in a JavaScript file?
Note: Of course, I understand that the templates would have to work very differently, since the AJAX call is getting its values from a JS object, not from the server. It's a long shot, but I thought I'd see if anyone's thought about this before.
I think it's something of a AJAX best-practice to pick one place to do your template rendering, either on the server or client. Yesod is (currently) oriented toward doing the rendering on the server.
This can still work with AJAX replacement of contents, though. Instead of getting a JSON response from the POST, you should get a text/html response that contains the result of rendering the template on the server with the values that would have been returned via JSON and then replacing the innerHTML of the DOM node that's being updated.
If you want to support both JSON and HTML responses (to support 3rd party applications via API or something) you would have to make the format of the response be a function of the request; either appending ".json" or ".html" to the URL or including a HTTP header that lists the specific document type required by the client.
It would be nice if Yesod provided a 'jwhamlet' template or something that would render the HTML via javascript in order to support client rendering, but I'm not aware of one. That's not to say there isn't one I'm not aware of, though, so keep an eye open for other answers.
If you wanted to make such a thing, you might try tweaking the hamlet quasi-quote code so that instead of expanding the quasi-quotes to an html-generating function, it expanded them to a JSON-generating function and a pre-rendered chunk of text that's a template in mustache-style such that the JSON returned by the function would provide the correct context for the template to be rendered the way you want.

Render partial view with jade on select change

I need to do the following,
I have a <select> (a list of team names), when the user selects a team, I get relevant information re: the team and display it.
How do I do this in jade?
I'm trying the following, (but I'm wrong obviously, I don't see a lot of documentation out there).
Briefly, I'm doing a include test.jade on my main page, and a res.render('test', {team: team_obj});
jade:
h1 #{team}.name
h2 #{team}.homeGround
h3 #{team}.manager
h4 #{team}.aka
nodejs:
collection.findOne(query, function(err, team_obj){
res.render('test', {team: team_obj});
});
I'm getting the information correctly in team_obj.
Get the following error when I run the app,
team is not defined
Now this is happening because test.jade is getting rendered before I feed it the team_obj.
Questions:
1) Am I doing this right? is include the correct way of partially rendering jade views? if yes, how do I make sure it renders only when the user has selected an option?
2) Is there a partial views concept in jade I'm unaware of?
1) you should use #{team.name}
2) you can't change the team object once the selector is changed. the template was rendered once with the database result. - such functionality should be handled by client side JavaScript and AJAX calls. partials in templates are just a way to share common pieces of templates, and its done in Jade via include.
I don't know what you're rendering and including and when.. but id you use a template variable like #{team.name} you have to make sure that the template was rendered with the team object.

jade / express - when to use or not to use layouts

I've just started developing in express and am new to Jade as well.
I'm having trouble deciding when it's appropriate to use layouts and when not to. I'm also having trouble deciding when it's appropriate to use something like blocks vs. partials.
Any help regarding this is truly appreciated. I'm a little lost.
It's mostly a matter of preference. If you are used to something like Wordpress where you have a concept of a header and footer that you include into pages than you might not like layouts. I personally only use layouts with content blocks because the non-layout way tends to cause more repetition.
As for partials vs blocks. You use a partial for items that you want to reuse on different pages. While a block is a chunk of html that will be replaced by child templates.
An example of a partial can be the html for a product. So you have a thumbnail, the title and a description of a product. You might use this partial while listing the products in a category. But you might also use this partial for rendering a list of search results.
An example of a partial can be a main layout that contains you header and your navigation and a content area. If you want to reuse this main layout on multiple pages you will extend this it and overwrite the block in the child templates.

How to provide the current route or view to the layout in ExpressJS?

I want to be able to dynamically reference JavaScript and Stylesheets depending on which page a user is on in Express. I thinking the best way to do so (though I'm open to suggestions) is to pass the current view to the layout page.
For example;
Given the url http://example.com/trees
I would want to have some logic in layout.jade that said something to the effect of:
script(src="/javascripts/{view}.js")
Which would get rendered as:
<script src="/javascripts/trees.js"></script>
Any suggestions or best practices for doing this?
req.route is the matched route, so things like req.route.path etc are available, or of course req.url which may be parsed. With express 2x you can expose these values to views automatically using "dynamic helpers" or res.local()
There are no best practices for doing this, since Express doesn't provide Rails like url helpers, so I think you're approach is fine.
The easy answer is to just put ALL your javascript into a single file and be done with it. Ditto for CSS. See the Ruby on Rails asset pipeline for details. You are probably making your life more complicated than necessary and also less efficient by having different javascripts on different pages.
However, since you asked, the answer for javascripts is easy. Just put the extra <script> tags in the view, not the layout. Problem solved. CSS doesn't work as cleanly because the <link> tags need to be inside the <head>. In this case, I define the styles I need as an array of strings and loop over that in my layout template. So in my route I set up a local variable such as
locals.css = ['/css/one.css', '/css/two.css']
Then just loop over that in your template and generate one <link> tag for each.

Recursive page assembling in Node.js with Express and Jade

I've been working on an API in Node.js for the first time, and of course I needed a test page so I decided to whip one up in Node as well for the hell of it.
After wracking my mind to come up with a good way to load the header, body and footer files (Jade syntax files) and have them be friends and render together, I came up with a recursive solution.
function assemblePage(name,markup)
{
markup = markup || '';
if (markup=='')
fs.readFile('header.jade', function(err,data){assemblePage(name,markup+data)});
else if (name != 'footer')
fs.readFile(name+'.jade', function(err,data){assemblePage('footer',markup+data)});
else
fs.readFile('footer.jade', function(err,data){console.log(markup+data);__res.send(jade.render(markup+data))});
}
So all I have to call is:
assemblePage('home');
Is this the best way to go about things?
I think you should be using expressjs(High performance, high class web development for Node.js) to render your templates.
It has a very sophisticated View Rendering. I think what you need is called view partials. In the screencasts section you can watch a screencast about view partials

Resources