4
votes

This is our Handlebars partial we've called input-field.
We're trying to dynamically create name and email fields based on the number of participants selected on the previous page.

<div class="form-group {{errors.fullName.class}}" id="fullName">
  <label for="full-name">Your full name</label>
  <p class="message-error">{{errors.fullName.message}}</p>
  <input type="text" class="form-control" name="fullName" value="{{values.fullName}}">
</div>

We have some functions which create and display error messages if any of those form fields are unfilled.
Instead of {{errors.fullName.class}}, we need it to be {{errors.fullName{{this}}.class}}.

We've found that Handlebars doesn't allow you to refer to another handlebars variable inside a handlebars statement this way.

It's all within an each loop:

{{#each otherOccupiers}}
   {{> input-field}}
{{/each}} 

Does anyone have an idea about how to achieve this effect, maybe by writing a handlebars helper function or some other way to perform this concatenation.

1
What are you intending {{this}} to evaluate to in {{errors.fullName{{this}}.class}}?76484
We were intending it to evaluate to evaluate to a number based on the which 'otherOccupier` we were on in the each loop. e.g. {{errors.fullName2.class}} or {{errors.fullName3.class}} We've thought about it some more and realised we probably shouldn't be putting logic in our view in this way which is likely why we're finding it hard to get Handlebars to do that.Katpas
It's very unclear what you are trying to achieve.76484

1 Answers

1
votes

I'm assuming the data object you are passing to handlebars looks something like this:

{
  otherOccupiers: ["A", "B"],
  errors: {
    fullName: {
      class: "error-class",
      message: "error-message"
    }
  }
}

However if you change the structure of your data object to look something like this:

{
  errors: {
    otherOccupiers: [
      "A" : {
        fullName: {
          class: "error-class",
          message: "error-message"
        }
      }
      "B" : {
        fullName: {
          class: "error-class",
          message: "error-message"
        }
      }
    ]
  }
}

Then you can do an each loop like this:

{{#each errors.otherOccupiers}}
  <div class="form-group {{this.fullName.class}}" id="fullName">
    <label for="full-name">Your full name</label>
    <p class="message-error">{{this.fullName.message}}</p>
    <input type="text" class="form-control" name="fullName">
  </div>
{{/each}}