twiggrav

twig: take an api and print it in html


i am using grav, and with twig i have an html file like this:

<div class="singlePostContainer">
    <span class="postNumber">
            01
    </span> 
    <div class="postTextContainer">
        <div class="postTitle">
            title
        </div>
        <div class="postDate">
            date
        </div>
        <div class="postAuthor">
            author
        </div>
    </div>
</div>

then I have this API: https://5efc440acf235d0016ad72be.mockapi.io/api/floating-point/floating-point

I want to take the data from that api (date, author etc) and print it inside the corresponding html div


Solution

  • Fetch the data and transform the JSON to an array, then pass it to your view, e.g.

    $api_data = json_decode(file_get_contents('https://5efc440acf235d0016ad72be.mockapi.io/api/floating-point/floating-point'), true);
    

    <div class="postTextContainer">
        <div class="postTitle">title</div>
        <div class="postDate">date</div>
        <div class="postAuthor">author</div>
    </div>
    {% for row in api_data %}
        <div class="postTextContainer">
            <div class="postTitle">{{ row.title }}</div>
            <div class="postDate">{{ row.date }}</div>
            <div class="postAuthor">{{ row.author }}</div>
        </div>
    {% endfor %}