Jleibham Jleibham - 1 month ago 14
HTML Question

For loop an array of objects in HubL?

Hi I have some javascript that is generating HTML code into hubspot, my client wants to have an easier access to editing content and I'm trying to set this up with a HubL template. I've found that I can right a for loop to print an array variables but I was curious if I'm able to print an array of objects?

Their code:

{% set languages = ['HTML', 'CSS', 'Javascript', 'Python', 'Ruby', 'PHP,', 'Java'] %}

{% for language in languages %}
<li>{{ language }}</li>
{% endfor %}


Simplified version of my code:

{ % set episodes = [{
id: "1",
name: "Episdoe 1"
}, {
id: "2",
name: "Episdoe 2"
}, {
id: "3",
name: "Episdoe 3"
}, {
id: "4",
name: "Episdoe 4"
}]
%}

<ul>{% for episode in episodes %}
<li>{{ episode.id }}</li>
<li>{{ episode.name}}</li>
{% endfor %}
</ul>


I'm currently getting an error for having the wrong syntax. The error is coming from having the brackets inside the []. I've tried looking on their site and did a bit of google searching but I can't seem to find anything on displaying an array of objects.

Answer

Should work! Here's a functional HubL template example using the object/data you provided above (with fixes):

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{ content.html_title }}</title>
    <meta name="description" content="{{ content.meta_description }}">
    {{ standard_header_includes }}
</head>
<body>
    {% set episodes = [
        {
            id: "1",
            name: "Episdoe 1"
        }, 
        {
            id: "2",
            name: "Episdoe 2"
        }, 
        {
            id: "3",
            name: "Episdoe 3"
        }, 
        {
            id: "4",
            name: "Episdoe 4"
        }
    ] %}

    <ul>{% for episode in episodes %}
      <li>{{ episode.id }}</li> 
      <li>{{ episode.name}}</li> 
      {% endfor %}
    </ul>

    {{ standard_footer_includes }}
</body>
</html>
Comments