Loop and Advertisments


#1

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>
			<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>
			<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>
			</div>
		</div>

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

	</div>

	


			{{else}}
			
			<h1>Trenutno nema dostupnih viceva.</h1>

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

#2

What I would do is put an #if

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

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


#3

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

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

 }

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


#4

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 }}

#5

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:


#6

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).


#7

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;
    }
 }

#8

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