Passing dynamic query-params as an object in link-to helper

I know this is super old, but I just ran into this exact issue, and I found a way to make it work. Note that I don’t think this is actually documented anywhere… I had to look at the source code to link-to to figure this out.

What you do is create a params array that you pass into link-to via the “params” attribute (eg. {{#link-to params=params}}). Each element of the array is a route segment (eg. [ 'cars', 'models', 'years' ]), and the last element can optionally be a special query param object of the format:

{
  isQueryParams: true,
  values: {
    key1: value1,
    key2: value2
  }
}

So in your case, I would set up a Computed property that contains all the params for each object in your model, as such:

processed: Ember.computed('model', function() {
  let data = this.get('model').map((obj) => {
    let params = [ myObject.routeName ];
    let queryParams = { isQueryParams: true, values: {} };
    if (obj.routeName === 'laptop') {
      queryParams.values.color = obj.param.color;
    }
    if (obj.routeName === 'mobile') {
      queryParams.values.size = obj.param.size;
    }
    if (obj.routeName === 'notebook') {
      queryParams.values.display = obj.param.display;
    }
    params.push(queryParams);
    return {
      routeName: obj.routeName,
      params: params
    };
  });
  return data;
}

And then in your template, it’d look something like:

{{#each processed as |data|}}
  {{#link-to params=data.params}}
    data.routeName
  {{/link-to}}
{{/each}}

Again, I don’t think using the params attribute of link-to or creating a query-params object as part of the params object is documented anywhere, so I don’t know how much of a hack this is.

4 Likes