3

I want to display in my template only the first element of an array. I've seen many topics including this one but it doesn't work in my case.

I have an helper like this:

Template.home.helpers({
  posts() {
    return Posts.find({});
  }
});

I would like to do something like this in my template:

{{posts.[0].title}}

I don't want to use a findOne in this case.

1
  • it should work. Are you sure it is not caused by already existing variable posts in data context or other name conflict? Or using it before collection is ready so it errors cause there is no such array in time of execution ? Commented Oct 28, 2015 at 14:59

2 Answers 2

2

Best to do this at the helper level, for example, this would add an optional index argument to the posts helper:

Template.home.helpers({
    posts(index) {
        if(typeof index !== "undefined" && index !== null){
            var data = Posts.find();
            return data[index];
        }
        else{
            return Posts.find();
        }    
    }
});

Then you set the data context and call it in blaze like this:

{{#with posts 0}}
    {{title}}
{{/with}}
Sign up to request clarification or add additional context in comments.

Comments

1

Just limit the size of the return set:

Template.home.helpers({
  posts() {
    return Posts.find({}, {limit: 1})
  }
});

Of course you'll probably want to sort it by something sensible as well, so that the first record is definitely the one you actually want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.