Meteor Iron-Router Layout Rendering - node.js

We have implemented a layout where the main content resides in dynamic sidebars. We defined following layoutTemplate:
<template name="layout">
{{> content}}
{{> leftbar}}
{{> rightbar}}
<nav class="navigation">
{{#if currentUser}}
{{> navigation_logged_in}}
{{else}}
{{> navigation_logged_out}}
{{/if}}
</nav>
</template>
We include e.g. the rightbar template in the layout template.
<template name="rightbar">
<aside class="rightbar">
<button id="closeRightBar" class="close-cross"></button>
{{yield 'rightbar'}}
</aside>
</template>
The rightbar template includes the rightbar yield where we yield the specific content into.
We have implemented following RouteController:
UserShowRouter = RouteController.extend({
before: function() {
var username = this.params.username;
if(App.subs.user) {
App.subs.user.stop();
}
App.subs.user = Meteor.subscribe('user', username);
},
waitOn: function () {
return Meteor.subscribe('user');
},
data: function() {
return Meteor.users.findOne({'profile.username': this.params.username});
},
action: function() {
this.render('profile', {to: 'rightbar'});
}
});
What we wanted to achieve is that for example the profile template is yielded into the rightbar yield and get's updated and re-rendered as the data changes.
The problem is now that the sidebars are dynamically animated, shown and hidden. Now every time the profile template gets re-rendered also the layout template gets re-rendered. Why is that? We thought one of the purposes of yield regions is that the whole site doesn`t need to be re-renderd. Now when the layout gets re-rendered the whole css of the animations are set back to the original values.
We now have tried several different approaches, but none of them seems to be a good and clean solution. Is there a way to keep the layout template from being re-rendered and just keep the yield region and template up-dated? Any suggestions or alternatives would be highly appreciated.

As I understand it, the behavior in which re-rendering of your templates "bubbles up" and causes re-rendering of their parent templates is not particular to iron-router or the way your code is implemented, but is inherent in Spark. Iron-router's {{yield}} pattern does not alter this behavior, as far as I can tell from its documentation.
The good news is that Spark is set to be replaced imminently with a newer, more fine-grained rendering engine, currently codenamed "Spacebars," which should alleviate the concern.
Here is a preview of the new rendering system:
https://github.com/meteor/meteor/wiki/New-Template-Engine-Preview
This talk from a week ago is also excellent at describing the benefits coming through the new rendering engine (while fairly long, an overview is given in the first 5 minutes):
https://www.youtube.com/watch?v=aPf0LMQHIqk
As for your options today, you can:
a) Use the {{#constant}} and {{#isolate}} parameters to try to limit re-rendering.
b) Work from a development branch as described in the link above:
You can play with the current work-in-progress version of the code using the template-engine-preview-4 release tag (run your app with meteor --release template-engine-preview-4), or by checking out the shark branch (it's an internal codename).
c) Best of all if the timeframe of your project allows is to allow the re-rendering to continue until Meteor 1.0 hits and "Spacebars" resides on the main branch - it sounds like this is 1-3 months away.

I think that the reason your layout template gets rerendered is because the data hook you implemented uses a reactive data source. If the current user object changes, the router probably decides to rerender the whole page because there is no simple way to decide which parts exactly depend on your reactive data.
If I'm right, a simple solution to your problem is to create a user helper that will fetch the necessary data only where they're actually needed, e.g.
Template.profile.user = function () {
return Meteor.users.findOne({/*...*/});
}
Then you can use it in your profile template along with the with helper (sic!), i.e.
{{#with user}}
...
{{/with}}
to prevent multiple calls to the Template.profile.user function.
Also, if I were you, I would use the data hook only for data which is required by templates in my layout.

Related

Editing Handlebars templates with ember and ember-cli

Hey so my problem is probably simple as I am brand new to ember and ember-cli, from what I understand you simply edit an applications HBS template containing the html, IE.
app/templates/settings.hbs
however my problem is that when I edit one of these files and restart the entire stack, no change is reflected - furthermore I'm basically just trying to create some minor changes to an already created stack by entering an if conditional to find the controller name and display content if it matches what im looking for,
for example
{{#if controller.name == "settings"}}
// diff lis
{else}
// normal lis
{#endif}
most importantly here, any changes I make at all to the HBS template does not seem to be reflected live, any idea why?
In addition to #Oren answer, if you're using ember 1.10 you can take advantage of handlebars subexpressions and write your own eq helper which could be used in more situations. For instance:
Ember.Handlebars.registerBoundHelper('eq', function(left, right) {
return left === right;
});
And then in your template
{{#if (eq name "settings") }}
// diff lis
{{else}}
// normal lis
{{/if}}
// ...
{{#if (eq something otherstuff) }}
// show this
{{else}}
// show that
{{/if}}
Live sample http://emberjs.jsbin.com/mezoxiqavi/1/edit
Handlebars does not have an equality helper in the form that you have posted. (See this list for a list of all of the built in helpers.)
Instead, what you need to do to make your code work is create a property on your controller:
IsNameSettings: function(){
return this.get('model.name') === 'settings';
}.property('model.name');
And change your template to use this property (note that you also have {{/endif}} which needs to be changed to {{/if}} [see the link above]):
{{#if controller.IsNameSettings}}
// diff lis
{else}
// normal lis
{/if}
See whether after changing your handlebars template to valid syntax as I described results in the page live updating when you are waiting for a live reload. Confirm that after saving these changes, you see output from ember-cli indicating a successful build. Check for output in the terminal along the lines of:
version: 0.1.12
Livereload server on port 35729
Serving on http://0.0.0.0:4200/
Build successful - 8891ms.

How to destroy growl div component that hides other stuff

On my jsf page at some point I send a message to the growl component.
<p:growl id="growlLong" for="growlLong" showDetail="true" life="10000" sticky="false"/>
Once the 10sec is over, or dismissed by clicking the X, the issue that occurs is the element below the growl is not selectable. By inspecting the components on the page, looks like the actual div stayed there and blocks the content below it.
<?xml version="1.0" encoding="UTF-8"?>
<div class="ui-growl-item">
<div class="ui-growl-icon-close ui-icon ui-icon-closethick" style="display: none;" />
<span class="ui-growl-image ui-growl-image-info" />
<div class="ui-growl-message">
<span class="ui-growl-title">Success!</span>
<p>Configuration successfully saved.</p>
</div>
<div style="clear: both;" />
</div>
So, the question is - how do I make this to go away and keep the content below still usable?
Here is the screenshot of the issue, as seen with "inspect element", blue boxes are existing links, red box is the dismissed growl. Inside the blue box, we can't click the part that is covered by the red box.
This topic might be older but I just recently stumbled upon it:
The reason that the showcase is working but my version was not was that I gave the .ui-growl CSS class a height AND a width. In the showcase, the size of the container is only defined by its content and thus 0 if there are no items to display.
I moved my height definition to .ui-growl-item (which is more appropriate anyhow) and now it's working like a charm.
While the it would be desirable to be able to tell growl to not leave behind the <div id="growlLong_container"> structure in the DOM, the simple solution is to just select it and remove it using your favorite method to manipulate the DOM.
The ID appears to be the ID you passed to growl: id="growlLong" + "_container". With a DOM ID it is a simple matter of selecting it and removing it.
Yes, it would be nice to be able to get growl to not leave it in there. However, there is a point of diminishing returns vs. the amount of effort you spend trying to find a solution. It appears to be well past the point where you should just use a hack and remove it. Make a note about it, move on. Leave a comment in the code that this is why you are making the DOM manipulation. A possibility rather than removing teh <div> is to adjust the z-index such that it is below that of the UI elements. Another possibility is to add display:none; to the style. Obviously, code it such that if the <div> is not there nothing goes wrong. Verify that the next use of growl still performs correctly.
Ask on the Growl discussion group. Submit it as a bug with growl. If a way surfaces to make growl not leave something like this in the DOM revisit the code and apply it.
As to removing it, if you have JavaScript available it is as simple as:
document.getElementById("growlLong_container").remove();
To be more specific we really need more information about your code and the environment in which you are running.
A "solution" that should remove the <div>:
Hopefully you will receive an answer which allows the elements to be hidden/removed by growl. However, there does not appear to be one at present.
The following script should wait around checking every 250ms to see if the <div id="growlLong_container"> has been entered into the DOM. Once the <div> has been entered into the DOM, the script will wait 10s. If the <div> exists after the 10s it will be removed. The script is a hack. But it should work.
You will need to place it such that it makes it onto the page, either enclosed in tags (as are here), or in a file without the first line:<script class="code" type="text/javascript"> and the last line: </script> removed. If you use a separate file you will need to have it included in a similar manner as you do jquery.js, foundation.js, foundation.topbar.js and foundation.tooltip.js.
<script class="code" type="text/javascript">
(function () {
"use strict";
const maxGrowlTime = 10000; //In milliseconds
const checkFrequency = 250; //In milliseconds
var intervalTimer=0;
var foundGrowl=false;
function dismissGrowl() {
var growlId;
growlId = document.getElementById("growlLong_container");
if(growlId) {
growlId.parentNode.removeChild(growlId);
}
foundGrowl=false;
setGrowlCheckInterval();
}
function checkForGrowl() {
var growlId;
if(foundGrowl) {
return;
}
growlId = document.getElementById("growlLong_container");
if(growlId) {
foundGrowl=true;
clearInterval(intervalTimer);
setTimeout(dismissGrowl, maxGrowlTime );
}
}
function setGrowlCheckInterval() {
intervalTimer = setInterval(checkForGrowl, checkFrequency );
}
setGrowlCheckInterval();
})();
</script>
My hope is that you find an answer that does not require a hack such as this. However, this should solve your problem, at least to an extent. With the script, the prevention of using those controls will last for at least the entire 10s up to 10.25s even if the user dismisses the growl early. With the two screenshots mentioned in the comments it would probably be possible to change the script such that it detects if the user dismisses the grow and then remove the <div> immediately. This would make it more responsive to user input.
This solution assumes that the <div id="growlLong_container"> does not exist in the DOM prior to your issuing the <p:growl id="growlLong" and that it is not needed afterwards. This is very likely because the ID of the dive appears to be composed of the ID you pass the growl.
Mainly, this issue looks like a bug or incompatibility issue between components.

Advanced Orchard Theming - Object Model vs Placement.info?

I have been tasked with converting a design heavy, fairly advanced HTML template for a site into an Orchard theme and I am struggling with the best way to accomplish certain things. The theme is built on bootstrap and is a modern responsive HTML template like you might find on ThemeForest or something. The site will have a number of content types (staff members, portfolio items, partners, etc.) and will need a number of templates. The content types will have a large number of fields (upwards of a dozen) inside of custom content parts.
Based on what I have read the proper way to do theming in Orchard is using placement.info in combination with alternates, wrappers, etc. This gracefully handles if parts or properties are added/removed. However, this technique is quickly becoming overwhelming, since I have to declare the name and order of every field/part in the placement.info for every content type, and every display type of that content type. Each field of each content type then needs to be wrapped in very specific html. This creates an issue because a single page can be split out into potentially a couple dozen views, with HTML tags opening in one view and closing in another.
The best work around for this I have found is to basically ignore the placement.info file and build templates just by traversing the object model. So basically, for a portfolio page, I would copy in the template HTML I have and then replace the text values with values from the model. This might look something like:
<li class="#Display(Model.ContentItem.PortfolioPart.PortfolioCore.Value.ToLower())">
<a href="#Url.ItemDisplayUrl(contentItem)" >
#foreach (var media in Model.ContentItem.PortfolioPart.PortfolioImage.MediaParts)
{
<img src="#Display(media.MediaUrl)" />
}
<span class="type">#Display(Model.ContentItem.PortfolioPart.PortfolioCoreArea.Value)</span>
<span class="portfolio-item-content">
<span class="header">#Display(Model.ContentItem.TitlePart.Title)</span>
<span class="body">
<p>
#Display(Model.ContentItem.PortfolioPart.PortfolioTagline.Value)
</p>
</span>
</span>
</a>
</li>
The benefit with this method is that I can apply all of the values in a couple of views and it's more readable. Obviously the problem with this is that if any properties or parts are removed, the template breaks.
Is there a way in Orchard to have the best of both worlds? I can't have a wrapper or template for every field - this would end up potentially hundreds of fields by the end. I also might need to display content types in multiple places with different views - each field would then require a whole new set of wrappers or alternates for every projection.
Please let me know if I'm missing anything or if there is a better way to do this besides manually traversing to the properties I need. I need a way to be able to easily plug in properties into very specific html.
My final thought was to use very specific templates for custom content types using the object model but still provide good general templates/placement.info file so that general Orchard content is flexible but the custom content types have to stay how they are.
Side thought - I guess another option would be to wrap any code that accesses a property directly in a try catch block or some kind of error handler helper, but that doesn't seem like a "best practice".
I think the techniques in this article are what you're looking for: http://weblogs.asp.net/bleroy/archive/2013/02/13/easy-content-templates-for-orchard-take-2.aspx

Passing arguments from node.js to knockout.js through ejs

I have a node.js that consumes mongodb data and outputs lists using knockout.js
When i invoke the view i pass a json structure using
res.render('list', { items:json });
In the list.ejs template page i've defined a hidden element:
<input type="hidden" id="hidden" value="<%= items %>">
and in .js file i read its value:
var json=$("#hidden").val();
var tkts=jQuery.parseJSON(json);
var vm=new AppViewModel(tkts);
Well...it runs but i think (hope) there must be a better way do it ... is there a way to avoid a hidden html var, for example?
Currently I can think of three ways to do this.
1.) Assign the data to a variable in your JavaScript code:
<script type="text/javascript">solution1 = {"name": "solution1"}</script>
solution1
2.) Add a data-attribute to an element of your liking:
<div id="solution2" data-value='{"name": "solution2"}'></div>
JSON.parse(document.getElementById('solution2').dataset.value)
3.) Use the script tag and choose a different content type than text/javascript or application/javascript
<script id="solution3" type="script" type="text/json">{"name": "solution3"}</script>
JSON.parse(document.getElementById('solution3').innerHTML)
Live demo
http://jsfiddle.net/bikeshedder/sbjud/
Personal note
It might sound boring, but the first option is probably the best choice. It is fast, requires as little code as possible and just works. I don't see a reason why you would want to have your data in a string first if you can have it as JavaScript data right away.
You could add an inline script if you are serving up a full page... Of course this would pollute the global namespace.
<script>
var tkts = <%= items %>;
</script>
If you are using AJAX to get this page... then break it into two AJAX requests... one of them gets the template, and the other one can get the list of items (as a JSON request). They could run in parallel so it might even be quicker.

modx create layout with chunk and call with template

I'm using modx revolution. I'd like to create a chunk called layout that calls other chucks example
Head
header
nav
body
footer
then in my template do something like //open layout tag[[$layout]] [[$layout]]//close layout tag. then inside of the the open close tags append my [[*content]]. this would allow me to reuse my layout template over and over again without having to replicate it in the templates. First question, is it possible, second what kind of syntax would be needed to achieve this goal? I'm rather new to modx and know it's possible with other frameworks, so any help would be appreciated. Thanks.
Sample concept done in Apache Tapestry framework, obviously different syntax, but should give you the general idea of what I'm looking for.
components/Chunks used.
Layout
Header
Nav
Footer
Inside of layout
<html>
<t:Header/>
<t:Nav/>
<t:Body/>
<t:Footer/>
</html>
Inside of Index/Template
<t:Layout>
template body content goes here ex. [[*content]]
</t:Layout>
Hope this helps to clarify.
Your post is not very clear and I think you haven't really taken much time to read up on how MODx works before looking for help.
That aside, I think what you want to do is create different templates, structured more or less like this:
[[$header]]
[[$nav]]
<div id="content">
<h1>[[*pagetitle]]</h1>
[[*content]]
</div>
[[$footer]]
That might do for your home page, then for internal pages where the layout is a bit different you can create one or more new templates for each layout:
[[$header]]
[[$nav]]
<div id="content">
<h1>[[*pagetitle]]</h1>
[[*content]]
</div>
[[$sidebar-chunk]]
[[$footer]]
You can even show different layouts using a single template something like this:
[[$header]]
[[$nav]]
<div id="content">
<h1>[[*pagetitle]]</h1>
[[*content]]
</div>
[[*parent:is=`6`:then=`
[[$recent-articles]]
`:else=`
[[$sidebar-chunk]]
`]]
[[$footer]]
That should get you started, but you'll soon realise there are multiple ways to do everything in MODx.
You can put your [[*content]] where-ever you want, even inside another chunk, if that's what you mean.
So your [[$layout]] chunk could just be this:
[[$header]]
[[$menu]]
<div id="content">
<h1>[[*pagetitle]]</h1>
[[*content]]
</div>
If you want to make some minor changes in a chunk on a template-basis you could also do something like this in the template:
[[$layout? &customContentBits=`
<h1>[[*pagetitle]]</h1>
[[*content]]
`]]
and your layout chunk could then be something like this:
[[$header]]
[[$menu]]
<div id="content">
[[+customContentBits]]
</div>
That's a placeholder ([[+customContentBits]]) which is set by adding the &customContentBits in the chunk call.
Explained that a tad more with a different use case on my blog some time ago too: http://www.markhamstra.com/modx-blog/2010/10/introducing-element-properties-and-output-modifier/
What you are asking can absolutely be done. In fact, on my website, I even have the same template/chunk combo providing multiple layouts by passing a template variable as a chunk modifier. But anyhow, let's keep things simple.
A quick note on your question., ModX doesn't use start tags and end tags, natively. It's best to stop thinking that way. Instead just place things where you want to place them. Resource variables can go in any chunk, as each resource is unique.
Create your Chunks:
First, start with the simple ones. Create your Header, Footer, and Navigation. Next, create your Body. Inside the Body, make sure to include your [[*content]] (no... it doesn't have to go into the Template. Finally, create your Layout with the following code:
[[$header]]
[[$navigation]]
[[$body]]
[[$footer]]
Create your Template:
Your template can now be as simple as [[$layout]]. You're done.
Note
While you can do this with ModX, understand that the power of ModX is that you can have multiple templates and chunks depending on the type of content you have. Singularizing everything like this really takes away a major advantage of using the platform.
Mark Hamstra more or less gave you the answer, but just to clarify: Any snippet, chunk or output of some sort in Modx can take parameters. Chunks and snippets especially can make use of these params easily. From what i understand you want to have all your templates call [[$layout]] and nothing else.
The layout chunk in turn looks like
[[$header]]
[[$navigation]]
[[$body]]
[[$footer]]
On this you simply build and add your params, nesting them down from the top like
[[$layout? &useNavigation=`1`]]
(And continue passing the param in your layout chunk)
[[$header]]
[[+useNavigation:is=`1`:then=`[[$navigation]]`]]
[[$body]]
[[$footer]]
Another way of accomplishing the same behaviour would be to use a single template to which you have connected a series of template variables that decide how the template looks like. You might have template variable called useNavigation of checkbox type. If you check this through the resource editor it will be passed to your $layout chunk directly without having to add params into the $layout chunk call.
[[$layout]]
(Just call layout normally and add the TV checks to the layout chunk directly.
Note the difference between calling a TV and a placeholder, + vs *)
[[$header]]
[[*useNavigation:is=`1`:then=`[[$navigation]]`]]
[[$body]]
[[$footer]]

Resources