Loop and Advertisments

Hello everyone. I’m learning MeteorJS few days now and its really awesome.
I would like to know how can I make that every 5 jokes it gives me an advertisment lets say something like that?

{{#each jokes}}
	<div class="joke">
		<div class="row">
			<div class=".col-sm-6 .col-md-5 .col-lg-6" id="info">
				<h1 class="joke-title">{{jokeName}}</h1>
				<p class="meta">Autor: {{author}}</p>
				<div class="meta">Objavljen: {{date}}</div>
			<div id="vote" class=".col-sm-6 .col-md-5 .col-md-offset-2 .col-lg-6 .col-lg-offset-0">
				<img src="laugh.png" class="smiley" id="laugh"  alt="">
				<img src="frown.png" class="smiley" id="frown"  alt="">
				<img src="puke.png" class="smiley" id="puke"  alt="">
			<div class="row" id="score">
				<h3 class="count red block">{{laughScore}}</h3>
				<h3 class="count yellow block">{{frownScore}}</h3>
				<h3 class="count green block">{{pukeScore}}</h3>

		<p class="regular joke-desc">{{jokePost}}</p>



			<h1>Trenutno nema dostupnih viceva.</h1>

 jokes: function() {
 	var jokes = Jokes.find({}, {sort: {createdAt: -1}});
 	return jokes;

What I would do is put an #if

{{#if isTimeForAd order}}
    <div ..><!-- ad here --></div>

You would need a field order which contains the index of the current joke and a helper isTimeForAd to check if its a multiple of 5


Thank You very much. You helped me alot with #if statment.

 isTimeforAd: function() {
 	var postnumber = Post.findOne({_id: this._id}).counter;
 		if (LastNumber % 5 === 0 ) {
 		return true;
 	} else {
 		return false;


And i used If statment to get my divs like you did :slight_smile:

You could also simply use the @index variable in the {{ #each }} loop.

It saves you from making a query in your Collection.

{{ #if isTimeForAd @index }}
{{ /if }}

I’m still learning and I’m don’t know how to work with @index variable…
Could You explain me how my isTimeforAd should look in JS?
And how to use it like that?
Thank You alot :slight_smile:

Almost exactly as you already did :slight_smile: .

In your {{ #each }}, just set @index as the argument of your helper.
Then your helper function will receive one argument, the index (which is a number). Test this index with a modulo 5 and return true / false (like in your previous post).

1 Like

To clarify what was mentioned by @borntodev. It is usually a better pattern to avoid making the same query multiple times in your template, so you can just pass @index (which is the current index in the #each iteration) to the template helper:

isTimeforAd: function(theIndex) {
     if (theIndex % 5 === 0) {
        return true;
    } else {
        return false;
1 Like

Thank You alot for your replays.
@rd010 thank You for this code that helped me too :slight_smile: