Okay, you can definitely generate your JSON API using Liquid templates in Eleventy. However, be aware that it requires careful handling of JSON syntax, especially commas and string escaping, which is inherently safer and easier using JavaScript templates (.11ty.js).
If you're set on Liquid, here's the best way to approach it:
1. Create the Liquid Template File
Create a file in your input directory where you want the API endpoint source to live. For an output file at /api/posts.json, a good source file name would be api/posts.json.liquid (or src/api/posts.json.liquid, etc.). The .json.liquid extension clearly indicates its purpose and tells Eleventy to process it as Liquid.
2. Define the Front Matter
At the top of your .liquid file, use YAML front matter to define the output path (permalink) and exclude it from Eleventy's standard collections:
---
permalink: /api/posts.json
eleventyExcludeFromCollections: true
---
3. Write the Liquid Template Structure
Now, write the Liquid code to generate the JSON structure. You'll loop through your desired collection (e.g., collections.post) and output JSON objects.
---
permalink: /api/posts.json
eleventyExcludeFromCollections: true
---
[
{%- assign posts = collections.post -%} {# Optional: Assign to variable for clarity #}
{%- for post in posts -%}
{
"title": {{ post.data.title | jsonify }},
"date": {{ post.date | date: "%Y-%m-%dT%H:%M:%SZ" | jsonify }}, {# Format date as ISO 8601 string, then jsonify #}
"slug": {{ post.fileSlug | jsonify }}, {# Or post.data.page.fileSlug #}
"url": {{ post.url | absoluteUrl | jsonify }}, {# Use custom absoluteUrl filter, then jsonify #}
"excerpt": {{ post.data.excerpt | default: "" | jsonify }} {# Handle optional excerpt, then jsonify #}
{# Add any other fields your app needs, always using the jsonify filter for strings #}
} {%- unless loop.last -%},{%- endunless -%} {# CRITICAL: Add comma unless it's the last item #}
{%- endfor -%}
]
Explanation and Key Points:
permalink: Sets the final output path and filename (/api/posts.json).
eleventyExcludeFromCollections: true: Prevents this API file from appearing in collections.all, etc.
[ and ]: Define the start and end of the JSON array.
- : Liquid tags with hyphens () control whitespace. Using them helps prevent extra newlines or spaces in your output JSON, keeping it clean.