Last active
September 10, 2024 17:12
-
-
Save peteheaney/231f488bac30e071ed74a2d747858834 to your computer and use it in GitHub Desktop.
Use Guzzle in a Craft CMS twig template. No need for a plugin!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# Create Guzzle instance #} | |
{% set client = create({ | |
'class': 'GuzzleHttp\\Client' | |
}) %} | |
{# Send API request #} | |
{% set response = client.request('GET', 'https://jsonplaceholder.typicode.com/posts') %} | |
{# Check the response status #} | |
{% set status = response.getStatusCode() %} | |
{# If the status is OK #} | |
{% if status == 200 %} | |
{# Decode the response contents #} | |
{% set posts = response.getBody().getContents() | json_decode %} | |
{# Loop through the content #} | |
<ul> | |
{% for post in posts %} | |
<li>{{ post.title }}</li> | |
{% endfor %} | |
</ul> | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment