[英]How to access global variables in Meteor template without using a helper?
我從不同的域提供了所有圖像文件,並將該主機名作為變量放入Meteor.settings中。 那么,如何在Meteor模板中訪問此變量?
例如,在此模板中,將img.example.com
替換為Meteor.settings或其他全局變量中定義的變量的最佳做法是什么? 我不認為通過使用幫助程序將它傳遞給每個模板是個好主意。
<template name="products">
{{#each items}}
<img src="http://img.example.com/{{id}}.png">
{{/each}}
</template>
您可以通過幫助程序將數據傳遞到模板的唯一方法。 您可以使用全局幫助器 :
Template.registerHelper('imgExampleUrl', function() {
return 'img.example.com';
});
然后,您可以在許多模板中使用全局幫助器:
<template name="products">
{{#each items}}
<img src="http://{{imgExampleUrl}}/{{id}}.png">
{{/each}}
</template>
<template name="otherTemplate">
<img src="http://{{imgExampleUrl}}/{{id}}.png">
</template>
或者,如果您想從settings.json獲取imgExampleUrl的值
Template.registerHelper('imgExampleUrl', function() {
return Meteor.settings.public.imgExampleUrl;
});
你的settings.json:
{
"public": {
"imgExampleUrl": "img.example.com"
}
}
在你的Js文件中這樣做。 它可能會幫助你
Template.yourTemplateName.varNameYouhavetoaccess= function(){
return getYourGlobalValueHere;
}
在模板的HTML頁面中,您可以迭代值{{varNameYouhavetoaccess}}
或者您可以使用Helper
在JS文件中:
Template.nametag.helpers({name:“Ben Bitdiddle”});
在HTML中:
<template name="nametag">
<p>My name is {{name}}.</p>
</template>
使用返回類型分配全局函數
if(Meteor.isClient){
getItems = function(){
//do your stuffs
return items;
}
你的模板
<template name="products">
{{#each items}}
<img src="http://{{imgExampleUrl}}/{{id}}.png">
{{/each}}
</template>
助手
Template.products.helpers({
items : function(){
return getItems();
}
});
您可以從任何地方使用getItems()
我知道這不是op所要求的,但是在搜索“如何從模板訪問Meteor設置”時,Google上出現了這個頁面。
我擴展了@Tomas Hromnik的靈魂,並制作了這個全局模板助手:
helpers.js
Template.registerHelper('meteorSettings', function(settings) {
var setting = Meteor.settings.public;
if (settings) {
var eachSetting = settings.split('.');
for (i = 0; i < eachSetting.length; i++) {
setting = setting[eachSetting[i]];
}
}
return setting;
});
home.html的
<template name="home">
<!--
Basically the same as doing this: (except you can't do this)
{{#if Meteor.settings.public.instagram.access_token}}
-->
{{#if (meteorSettings 'instagram.access_token')}}
<div class="instagram"></div>
{{/if}}
<!--
You can also set Meteor.settings.public to a variable to access multiple settings
-->
{{#let settings=meteorSettings}}
{{settings.instagram.access_token}}
{{/let}}
</template>
Template.registerHelper('var', name => {
const data = Template.instance().data || {};
return data[name];
});
內部模板:
{{var 'someVariableFromTemplate'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.