Search code examples
jquerygofullcalendarsmarty

Golang + JQuery + Smarty: How to iterate over object?


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>

Solution

  • 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}}
    ]
    

    https://play.golang.org/p/LBDBAMY4cL