Search code examples
clojureluminusselmer

Looping through JSON in a Selmer template


I`m making simple quiz game and want to store the questions in a JSON file like so:

{"questions":
    [  
      {  
         "question":"2+2 ?",
         "answer_A":1,
         "answer_B":2,
         "answer_C":3,
         "answer_D":4,
         "correct_answer":4
      },
      {  
         "question":"2+3?",
         "answer_A":1,
         "answer_B":2,
         "answer_C":3,
         "answer_D":5,
         "correct_answer":5
      }    
  ] }

This is code to load it from file:

defn json-page []
(layout/render
    "json.html" {:file (parse-string (slurp "path/to/file"))}))

parse-string return a string, so I cannot loop over it to display every element. How can I do this? I know the syntax ({% for question in file %}), but I don't know how to access nested elements.


Solution

  • Thanks to Reddit for answer :

    (defn json-page []
        (layout/render
            "json.html" {:file (parse-string (slurp "path/to/file") true)}))
    

    The answer was to add true as a parameter for parse-string to keywordize the json maps. After this I can loop over json :

    {% for question in file.questions %}
            <p>{{ question.question }}.</p>
            {{ question.answer_A}}
            {{ question.answer_B}}
            {{ question.answer_C}}
            {{ question.answer_D}}
     {% endfor %}