Pass spacebar parameter to another spacebar parameter - javascript

Im trying to pass a parameter from one template to other in meteor.js
i want to do this for DRY sake
The first template looks like this
template(name="myPage")
h3.uppercase.amarillo-hogar
+editaMl(data=this collection="categorias" field="titulo")
template(name="editaMl")
if i18n_isCurrentLanguage 'es'
| {{collection}} {{field}}
+editableText(context=data collection=collection field=field userCanEdit=userCanEdit acceptEmpty=true substitute='<i class="fa fa-pencil"></i>')
else
+editableText(collection=collection field=field userCanEdit=userCanEdit acceptEmpty=true substitute='<i class="fa fa-pencil"></i>')
this is so i can stop repeating myself with every translation field
but cant work around passing a parameter value to another template parameter value
i use jade, now in html for those who do not like jade
<template name="myPage">
<h3 class="uppercase amarillo-hogar>{{> editaMl collection="categorias" field="titulo"}}</h3>
</template
<template name="editaMl">
{{#if i18n_isCurrentLanguage 'es'}}
{{> editableText collection=collection field=field }}
{{/if}}
{{#else}}
{{> editableText collection=collection field=field }}
{{/else}}
</template>
just if you want to know, im using babraham editable text package and tap_i18n with tap_i18n ui for translating
Cant find the reason my helper returns an object when used like this in the content {{collection}} but when used as parameter in the child template does nothing
Code updated and SOLVED

You can use:
Template.registerHelper('yourHelperName', function() {
// your helper
});
It creates a helper available in all templates.

Related

How to assign local variable in Jquery template

Below, I am trying to print replaced items using Jquery template. There I want to set a variable partHasBeenReplaced which later I can use to print the label and close the <span> element.
How can I set variable there?
How to find the last element of type "REPLACEMENT"? it may not be the last element of the array.
{{each(i,ref) productReferences}}
{{if ref.referenceType == 'REPLACEMENT'}}
{{partHasBeenReplaced = 'true'}}
{{/if}}
{{/each}}
{{if partHasBeenReplaced == 'true'}}
<span class="text-danger font-weight-bold pt-2">
This item has been replaced with:
{{/if}}
{{each(i,ref) productReferences}}
{{if ref.referenceType == 'REPLACEMENT'}}
{{= ref.target.code}} ,
{{/if}}
{{/each}}
{{if partHasBeenReplaced == 'true'}}
</span>
{{/if}}
In order to assign data to an element using such templates, it better to use attributes. We can access create/update/remove attribute using JavaScript.
For an example, if you want to add a data for <span> then you can do it using -
<span id="mySpan" class="text-danger font-weight-bold pt-2" partreplaced="{{partHasBeenReplaced}}" ></span>
It can be accessed in JavaScript using below method -
let span = document.querySelector("#mySpan");
let partreplaced = span.getAttribute('partreplaced');
console.log(partreplaced); //will print which was set in that attribute using the templating engine.
There is no simple solution to set the local variable as we do in JSTL. So what I did is I have used JS to populate final flag like partHasBeenReplaced and set it to data before passing it to Jquery template. So that I can directly use the variable in the template.

How to use getElementById with a reactive var and Meteor

In general doing a getElementById works pretty well like this :
console.log(document.getElementById('{{chart_id}}').setAttribute("id", "div_top2"));
But it returns me null and I don't really know why but I think it's becoming from the following lines:
<template name="chart">
<div id="{{chart_id}}"></div>
</template>
And later in the JS I do :
Template.currentData().chart_id
to get the div and place a HighChart here.
The thing I want to do is to rename the id (by the way I want to add a identifier so the final id would be something like <div id ="{{chart_id}}+ a random number">)
Then I could do this in my JavaScript:
Template.currentData().chart_id + theRandomNumber
Finally I have modified the HTML where I create the <div> and it looks like this :
{{#each gimmeContainersToCreateChart}}
{{> chart chart_id=this._id}}
<!-- {{> chart chart_id="cpuChart"}}
{{> chart chart_id="netChart"}}
{{> chart chart_id="diskChart"}} -->
{{/each}}
gimmeContainersToCreateChartreturns a cursor with the running&&paused containers from the collection

javascript get value of Mongo field already rendered - Meteor

Hey everyone, thank you very much for your help. Question is edited per suggestions in the comments.
I'm new to Mongo and Meteor.
I have a collection "posts" with a field "slug".
The "post" template is populating correctly with each post's values. Slug value is always something like "my-great-post".
I need to get the text value for the _id's slug, which will be different each time the template is accessed, encode it, write a string, and spit the string back out into the template.
Things tried
can't return a value for "this.slug" or "this.data.slug" in either template helpers or onRendered, even though collection is defined and correctly populating spacebars values in the template
"this" returns "[object Object]" to console.log
app crashes when I try to javascript encode and deliver a string from the helper, probably I don't fully understand helper syntax from the documentation
(I followed advice in the comments to avoid trying to create scripts in the template html, so below is more information requested by everyone helping on this thread)
- Template html -
{{#with post}}
<div class="blog-article">
<div class="blog-header">
<div class="left">
<!-- title -->
<h1 class="post-title">{{title}}</h1>
<div class="holder">
<div class="post-tags">
<!-- tags -->
{{#each tags}}
<span>{{this}}</span>
{{/each}}
</div>
</div>
</div>
</div>
<div class="blog-post">
<div class="blog-copy">
<!-- date -->
<div class="post-date">{{post_date}}</div>
<!-- social -->
<div class="blog-social">
<!--
<a class="so-facebook" target="_blank" href="need to encode slug here"></a>
-->
</div>
<!-- ============== post ============== -->
{{{content}}}
<!-- ============ end post ============ -->
</div>
</div>
</div>
{{/with}}
- Template js -
Template.post.onCreated(function() {
var self = this;
self.autorun(function() {
var postSlug = FlowRouter.getParam('postSlug');
self.subscribe('singlePost', postSlug);
});
});
Template.post.helpers({
post: function() {
var postSlug = FlowRouter.getParam('postSlug');
var post = Posts.findOne({slug: postSlug}) || {};
return post;
}
// can't get these working in a helper, out of helper they crash the app
// console.log(this.slug);
// console.log(this.data.slug);
});
Template.post.onRendered( function () {
// these do not work
// console.log(this.slug);
// console.log(this.data.slug);
});
db.posts.findOne();
{
"_id" : ObjectId("576c95708056bea3bc25a91f"),
"title" : "How Meteor Raised the Bar For New Rapid-Development Technologies",
"post_date" : "May 28, 2016",
"image" : "meteor-raised-the-bar.png",
"slug" : "how-meteor-raised-the-bar",
"bitlink" : "ufw-29Z9h7s",
"tags" : [
"Tools",
"Technologies"
],
"excerpt" : "sizzling excerpt",
"content" : "bunch of post content html"
}
If some one can solve this using any method, I will accept answer with joy and gratitude most intense.
The problem is probably with the parent template, rather than this one. The way that Meteor works is that the JS files are separated from the HTML, so don't try to include a <script> tag in the HTML.
The first thing is that you have to load all of your documents into the client. (NOTE: once you've got the hang of that, then you can worry about only loading the documents that you need).
To do that, you need a collection and a publication. By default all collections are automatically published completely, so unless you removed the autopublished module, then I'll assume that it is still loaded.
So let's start with the parent template. In this case, I'm going to just loop through all of the posts in the collection and display them using the innerTemplate.
<template name=parent>
<ul>
{{#each post}}
{{> innerTemplate}}
{{/each}}
</ul>
</template>
And now our inner template might look like this:
<template name=innerTemplate>
<li>{{slug}}</li>
</template>
The end result will be a simple list with each slug.
Now, to link everything together, we need to create a JS file, which will:
1. define the collection on both client and server
2. pass the collection to the parent template
This file should be accessible to both the client and the server.
posts = new Mongo.Collection('posts');
if(Meteor.isClient) {
Template.parent.helpers({
posts() {
return Posts.find();
}
});
}
Now, if you want to do something with 'slug' in the JS file, you could do something like this:
if(Meteor.isClient) {
Template.innerTemplate.helpers({
upperCaseSlug() {
return this.slug.toUpperCase();
}
});
}
Then, you could refer to upperCaseSlug in your template, like thus:
<template name=innerTemplate>
<li>{{upperCaseSlug}}</li>
</template>
A few things about Meteor:
You should never see a pattern such as:
<script type="text/javascript">
...some code
</script>
Because Meteor combines all your js files into one big file and includes it automatically in your app. You should never have to declare your own script in this way.
Secondly, you should never have to get the value of a data object by reading the DOM. The data context of each template gives you your data in the variable this.
In either a helper or template event you can refer to this and be assured that you're going to get exactly the data being displayed in that instance of the template.
Having now seen your template code it's now apparent that your template has no data context - you set the data context inside your {{#with post}} and its associated helper but that doesn't end up creating the this you need one level below.
So... #Nathan was on the right track except that he assumed you were iterating over a cursor instead of just looking at a single post.
Take all html you have between your {{#with post}} and {{/with}} and put it in a new template, say postDetail then make your outer template:
<template name="post">
{{#with post}}
{{> postDetail}}
{{/with}}
</template>
Now your postDetail template will get a data context equal to the post object automatically and your helpers can refer to this safely.
Template.postDetail.helper({
slugURI{
return "/"+encodeURI(this.slug);
}
});
Then in your postDetail template you can get the encoded slug with:
<a class="so-facebook" target="_blank" href={{slugURI}}>

How to execute a callback after an #each is done?

I'm having trouble with a callback after the #each has finished. I have a template named "content":
<template name="content">
{{#if Template.subscriptionsReady}}
{{#each currentData}}
<div data-cid="{{this._id}}"></div>
{{/each}}
{{else}}
Loading...
{{/if}}
</template>
At first I wait for a subscription, when this is available, I iterate through my Collection with {{#each}} and append the div. What I need is a sort of callback for when the for-each loop is done (in other words DOM ready).
Template.content.onRendered()
-> triggers to early
I also tried appending an image after the {{each}} and fire a function in its onload like this:
<img style="height:0;width:0" src="*mysource*" onload="callback()">
-> did work sometimes but not reliable somehow
Is there a way to get this callback? I do not fear to change the structure of this template, if that brings the solution.
There's no easy way to get notified when a Spacebars {{#each}} block has done rendering into the DOM every item getting iterated over.
The best solution is to use another reactive computation (Tracker.autorun) to observe your (reactive) current data.
Everytime your current data (which is likely a cursor) is modified, you can run arbitrary code after every other reactive computations are done performing whatever their job is, using Tracker.afterFlush.
The {{#each}} block is one of those computations, whose role is to listen to the reactive data source you give it as argument and rerender its Template.contentBlock as many times as items fetched from the source being iterated over, with the current item as current data context.
By listening to the exact same reactive data source as the {{#each}} block helper and running your code AFTER it has finished its own reactive computation, you can get the actual requested behavior without relying on some weird tricks.
Here is the full implementation of this pattern :
JS
Template.content.helpers({
currentData: function(){
return Template.currentData();
}
});
Template.content.onRendered(function(){
this.autorun(function(){
var cursor = Template.currentData();
// we need to register a dependency on the number of documents returned by the
// cursor to actually make this computation rerun everytime the count is altered
var count = cursor.count();
//
Tracker.afterFlush(function(){
// assert that every items have been rendered
console.log(this.$("[data-cid]") == count);
}.bind(this));
}.bind(this));
});
I had a similar problem and after a lot of searching found the following solution. I tried using Tracker, onRendered and other tricks, none of them worked. This could be considered more of a hack, but works. Unfortunately can't remember where I found this solution initially.
Start with your template, but add an template tag after your each.
<template name="content">
{{#if Template.subscriptionsReady}}
{{#each currentData}}
<div data-cid="{{this._id}}"></div>
{{/each}}
{{doneTrigger}}
{{else}}
Loading...
{{/if}}
</template>
Then define a helper that returns null.
Template.content.helpers({
doneTrigger: function() {
Meteor.defer(function() {
// do what you need to do
});
return null;
}
});
You can read more about Meteor.defer() here, but it is equivalent to using a 0 millisecond setTimeout.
You can also use sub-templates and count the number of sub-templates rendered. If this number is the number of items in the collection, then all are rendered.
<template name="content">
{{#if Template.subscriptionsReady}}
{{#each currentData}}
{{> showData}}
{{/each}}
{{else}}
Loading...
{{/if}}
</template>
<template name="currentData">
<div data-cid="{{this._id}}"></div>
</template>
With that, initialize a reactive variable and track it:
var renderedCount = new ReactiveVar(0);
Tracker.autorun(function checkIfAllRendered() {
if(renderedCount.get() === currentData.count() && renderedCount.get() !== 0) {
//allDataRendered();
}
});
When the currentData template is rendered, increment it, and decrement it when it is destroyed.
Template.currentData.onRendered(function() {
renderedCount.set(++renderedCount.curValue);
});
Template.currentData.onDestroyed(function() {
renderedCount.set(--renderedCount.curValue);
});
A possibly simpler approach to consider - create a template around your #each block and then get an onRendered event afterwards:
html:
<template name="content">
{{#if Template.subscriptionsReady}}
{{> eachBlock}}
{{else}}
Loading...
{{/if}}
</template>
<template name="eachBlock">
{{#each currentData}}
<div data-cid="{{this._id}}"></div>
{{/each}}
</template>
js:
Template.eachBlock.onRendered(function(){
console.log("My each block should now be fully rendered!");
});

I want Handlebar {{#if}} logic inside of a Ember.Handlebars.helper

I am converting someone else's code to Handlebars.js and I'm stuck on converting this tag to its {{#handle-bar}}{{/handle-bar}} counterpart.
The previous coder used an {{#ifCond}} to toggle what 'selected'. This is my component.
{{#dropdown-item }}
{{unbound this.itemName}}
{{/dropdown-item}}
Here is the div i want converted to my component
<div class="dropdownItem" {{bind-attr value=formField_DropdownItemID}}{{#ifCond formField_DropdownItemID value}} selected{{/ifCond}} >
{{unbound this.itemName}}
</div>
My first thought was to just pop the div's logic into the the component, like the next example, but this gave me an error.
{{#dropdown-item bind-attr value=formField_DropdownItemID {{#ifCond formField_DropdownItemID value}} selected{{/ifCond}} }}
{{unbound this.itemName}}
{{/dropdown-item}}
Any suggestions?
You can set those properties to compute. The syntax would be:
{{#dropdown-item selected=computedProperty value=formField_DropdownItemID}}
computedProperty can deal with your conditional logic. The whole idea is to pull that out of handlebars anyways. :)

Categories

Resources