英文:
Golang + JQuery + Smarty: How to iterate over object?
问题
Golang服务器正在将schools
对象发送到print.tpl
Smarty文件,如下所示:tplData["Schools"] = schools
在print.tpl
文件中,我可以使用以下代码打印它:
{{range $.Schools}}
{{.Course}} -- {{.Duration}}
{{end}}
在print.tpl
文件中,我需要使用https://fullcalendar.io JQuery组件,并且它可以与以下静态数据正常工作:
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today myCustomButton',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
events: [
{
title : 'event1',
start : '2017-08-01'
}
]
});
});
</script>
问题:如何在我的JQuery函数中迭代$.Schools
对象?
注意:在Golang中托管REST并在JQuery中调用是一种选择,但我不想选择这种方法。
更新:根据@mkopriva的出色答案,更新了增强代码:
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today myCustomButton',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
events: [
{{range $.Schools}}
{
title : {{.Course}},
start : {{.Duration}}
},
{{end}}
]
});
});
</script>
英文:
Golang server is sending schools
object to print.tpl
smarty file like: tplData["Schools"] = schools
In print.tpl
file, I am able to print it using below:
{{range $.Schools}}
{{.Course}} -- {{.Duration}}
{{end}}
In print.tpl
file, I need to use https://fullcalendar.io JQuery component and it works fine with static data like below:
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today myCustomButton',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
events: [
{
title : 'event1',
start : '2017-08-01'
}
]
});
});
</script>
Question: How can I iterate $.Schools
object in my JQuery function?
Note: Hosting REST in Golang and calling in JQuery is an option, but I don't want to go that route.
Update: New enhanced code as per @mkopriva brilliant answer:
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today myCustomButton',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
events: [
{{range $.Schools}}
{
title : {{.Course}},
start : {{.Duration}}
},
{{end}}
]
});
});
</script>
答案1
得分: 2
Go模板支持js和css,并且actions({{ ... }}
)的评估是有上下文的,所以你可以像在html中一样在js中迭代学校。虽然我不知道smarty是什么,所以如果这不起作用,你需要查看smarty的文档。
events: [
{{range $.Schools}}
{
title: {{.Course}},
start: {{.Duration}}
},
{{end}}
]
https://play.golang.org/p/LBDBAMY4cL
英文:
Go templates support js and css and the evaluation of actions ({{ ... }}
) is contextual so you can iterate over schools in js the same as you do in html. Although I have no idea what smarty is, so if this isn't working you need to check smarty's documentation.
events: [
{{range $.Schools}}
{
title: {{.Course}},
start: {{.Duration}}
},
{{end}}
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论