Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access global variables in Meteor template without using a helper?

I have all my image files served from a different domain, and I put that host name as a variable into Meteor.settings. Then, how can I access this variable within a Meteor template?

For example, in this template, what's the best practice to replace img.example.com with a variable defined in Meteor.settings or some other global variables? I don't think it's a good idea to pass it to every template by using helpers.

<template name="products">
  {{#each items}}
    <img src="http://img.example.com/{{id}}.png">
  {{/each}}
</template>
like image 589
zhengyue Avatar asked Apr 24 '15 05:04

zhengyue


1 Answers

The only way how you can pass data into your templates is via helpers. You can use global helper:

Template.registerHelper('imgExampleUrl', function() {
   return 'img.example.com';
});

Then you can use global helper in many templates:

<template name="products">
  {{#each items}}
    <img src="http://{{imgExampleUrl}}/{{id}}.png">
  {{/each}}
</template>

<template name="otherTemplate">
    <img src="http://{{imgExampleUrl}}/{{id}}.png">
</template>

Or if you want to get value of imgExampleUrl from settings.json

Template.registerHelper('imgExampleUrl', function() {
   return Meteor.settings.public.imgExampleUrl;
});

Your settings.json:

{
  "public": {
    "imgExampleUrl": "img.example.com"
  }
}
like image 150
Tomas Hromnik Avatar answered Oct 27 '22 08:10

Tomas Hromnik