meteorcollectionsmeteor-blaze

Providing a data context for a dynamic template from a route parameter


I have an app that will potentially have hundreds of different forms (created by users).

To tackle this problem my plan is to a collection of forms whereby each document includes the following:

{
  formTitle: "form title goes here",
  version: 1.0,
  fieldsets: [
    {
      fieldsetTitle: "Personal information",
      introMessage: "Please provide your name and date of birth",
      inputs: [
        {
          label: "Full name",
          type: "text",
          placeholder: "John Doe"
        },
        {
          label: "Date of birth",
          type: "date",
          placeholder: "DD/MM/YYYY"
        }
      ]
    }
  ]

At present I have my blaze template inclusion with a formName var as follows:

  {{> form formName="form title goes here" }}

  Template.form.onCreated(function(){
      var thisFormName = this.data.formName; // this returns fine
      var thisForm = Forms.findOne({formName: thisFormName}); //also works fine
      console.log(thisForm); // prints the form document to console
  })

I cannot however, access this data within my template.

 <template name="form">
      {{thisForm.formTitle}} // doesn't print the title and as such I cannot use the document within the template.
 </template>

As this is a template for a module I cannot grab the data through routing (as far as I believe).

Does anyone have any idea what I'm missing?

I'm sure it's due to the template rendering before the document is returned from the collection however I'm unsure how to remedy this issue (as I can't use routing wait functions such as waitOn)

Thanks in advance.


Solution

  • You need to create a data context for blaze:

    html:

    <template name="form">
      <!-- at this point the data context only includes 'data.formName' ->
      {{#with thisform data.formName}}
        {{this.formTitle}}
      {{/with}}
    </template>
    

    js:

    Template.form.helpers({
      thisForm: function(name){
        return Forms.findOne({formName: name});
      }
    });
    

    Your onCreated code merely creates two local variables,