Search code examples
meteoriron-routermeteor-blaze

How to fetch query parameters in a template?


I am using Meteor 1.2.1 + iron-router with autopublish turned on

I would like to construct an anchor href based on collection values returned by a helper and query params

Is it possible to do this in the template tag, e.g. query_param1 should be read from the URL?

<template name="dataEntry">
  {{#each data}}
    <li>
      <a href="/listing?name={{name}}&color=<query_param1>">
       Data name
      </a>
    </li>
  {{/each}}
</template>

Above, {{name}} is returned by the collection and query parameters are appended to that to create a full hyperlink for the href.


Solution

  • You can use @Stephen's suggestion like this.

    In your template html,

         <template name="dataEntry">
            {{#each data}}
                <li>
                    <a href="/listing?{{queryParams}}">
                        Data name
                    </a>
                </li>
            {{/each}}
        </template>
    

    In your template JS,

    Template.dataEntry.helpers({
       "queryParams": function () {
           var name = "";
           //get name from collection here like...
           //name = Meteor.user().profile.firstName;
           var color = Router.current().params.color;
           return "name=" + name + "&color=" + color;
        }
    });
    

    Or you can use two separate helpers

    In your template html,

         <template name="dataEntry">
            {{#each data}}
                <li>
                    <a href="/listing?name={{name}}&color={{color}}">
                        Data name
                    </a>
                </li>
            {{/each}}
        </template>
    

    In your template JS,

    Template.dataEntry.helpers({
       "name": function () {
           var name = "";
           //get name from collection here like...
           //name = Meteor.user().profile.firstName;
           return name;
        },
       "color": function () {
           return Router.current().params.color;
        }
    });