Skip to content
TheChatArchiveThe Chat Archive
Metallama-4-maverick-17b-128e-instruct· MetaHugging Face LMArena Human Preference 140K

I have an 11ty website that I regularly update. I'd like to create an iOS app that gets…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-pro-preview-03-25’s answer.
  1. User

    I have an 11ty website that I regularly update. I'd like to create an iOS app that gets its content via a JSON api that's generated by the 11ty website, and is updated any time new content is available. What's the best way to generate that JSON API in 11ty

  2. Meta Assistant

    To generate a JSON API in 11ty, you can leverage 11ty's ability to output JSON files alongside HTML files. Here's a step-by-step guide to help you achieve this:

    1. Create a JSON Template

    First, you'll need to create a template that outputs JSON instead of HTML. Let's say you want to create a JSON feed for your blog posts.

    Create a new file in your _includes directory, e.g., posts.json.njk. The .njk extension indicates it's a Nunjucks template, but you can use any templating engine supported by 11ty.

    {
      "posts": [
        {% for post in collections.posts %}
        {
          "title": "{{ post.data.title }}",
          "url": "{{ post.url }}",
          "date": "{{ post.date | date('yyyy-MM-dd') }}",
          "content": "{{ post.templateContent | striptags(true) | escape }}"
        }{% if not loop.last %},{% endif %}
        {% endfor %}
      ]
    }
    

    This template iterates over your posts collection, outputting a JSON object for each post.

    2. Configure 11ty to Output the JSON File

    To output this template as a JSON file, you'll need to add a permalink to the template's front matter. Create a new file in your project's root directory (or a subdirectory if you prefer), e.g., posts.json.njk, and include the following front matter and template content.

    ---
    permalink: "/api/posts.json"
    layout: "layouts/json/posts.json.njk"
    eleventyExcludeFromCollections: true
    ---
    

    The permalink sets the output path for the generated JSON file. The layout references the template you created in step 1. eleventyExcludeFromCollections is set to true to prevent the JSON file itself from being included in your collections.

    3. Customize the JSON Output

    You can customize the JSON output by modifying the template. For example, you might want to include more metadata or change how the content is processed.

    4. Update Your iOS App to Consume the JSON API

    Once your 11ty site generates the JSON API, update your iOS app to fetch and parse this JSON. You can use URLSession for fetching and a JSON parsing library like Codable or a third-party library.

    5. Handling Updates

    To keep your iOS app updated with the latest content, consider implementing a mechanism to check for new or updated content. This could involve:

    • Polling: Regularly fetch the JSON API to check for updates. This is straightforward but can be resource-intensive.
    • Webhooks: If your 11ty site is hosted on a platform that supports webhooks (e.g., Netlify), you can configure a webhook to notify your server (if you have one) when the site is updated. Your server can then notify your iOS app via push notifications or another mechanism.
    • Last-Modified Header or ETag: When fetching the JSON, check the Last-Modified header or ETag to determine if the content has changed since the last fetch.

    Example Use Case

    For an iOS app, you might fetch the JSON data when the app launches or when the user pulls to refresh. Here's a simple example using Swift and URLSession:

    func fetchPosts(completion: @escaping ([Post]) -> Void) {
        guard let url = URL(string: "https://your-11ty-site.com/api/posts.json") else { return }
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("Error fetching posts: \(error)")
                return
            }
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                let postsResponse = try decoder.decode(PostsResponse.self, from: data)
                completion(postsResponse.posts)
            } catch {
                print("Error decoding JSON: \(error)")
            }
        }.resume()
    }
    
    struct PostsResponse: Codable {
        let posts: [Post]
    }
    
    struct Post: Codable {
        let title: String
        let url: String
        let date: String
        let content: String
    }
    

    This example assumes you have a Post struct that conforms to Codable, matching the structure of your JSON output.

    By following these steps, you can create a JSON API with 11ty and consume it in your iOS app, keeping your app's content up to date with your website.

  3. User

    I'd like to do any templating in liquid

  4. Meta Assistant

    To generate a JSON API in 11ty using Liquid templating, you can follow a similar process as before, but with Liquid templates instead of Nunjucks.

    1. Create a Liquid Template for JSON Output

    Create a new file in your _includes directory, e.g., posts.json.liquid. This will be your template for generating the JSON output.

    {
      "posts": [
        {% for post in collections.posts %}
        {
          "title": "{{ post.data.title | escape }}",
          "url": "{{ post.url }}",
          "date": "{{ post.date | date: '%Y-%m-%d' }}",
          "content": "{{ post.templateContent | strip_html | escape }}"
        }{% unless forloop.last %},{% endunless %}
        {% endfor %}
      ]
    }
    

    This Liquid template iterates over your posts collection and outputs a JSON object for each post. Note the use of Liquid's escape filter to ensure that the output is properly escaped for JSON.

    2. Configure 11ty to Output the JSON File

    To output this template as a JSON file, you'll need to add a permalink to the template's front matter. Create a new file in your project's root directory (or a subdirectory if you prefer), e.g., posts.json.liquid, and include the following front matter and template content.

    ---
    permalink: "/api/posts.json"
    layout: "posts.json.liquid"
    eleventyExcludeFromCollections: true
    ---
    

    The permalink sets the output path for the generated JSON file. The layout references the Liquid template you created in step 1. eleventyExcludeFromCollections is set to true to prevent the JSON file itself from being included in your collections.

    3. Customize the JSON Output

    You can customize the JSON output by modifying the Liquid template. For example, you might want to include more metadata or change how the content is processed.

    4. Update Your iOS App to Consume the JSON API

    The process for updating your iOS app remains the same as before. You'll need to fetch and parse the JSON output from your 11ty site.

    5. Handling Updates

    The strategies for handling updates also remain the same: polling, webhooks, or checking the Last-Modified header or ETag.

    Example Use Case

    The example use case for fetching and parsing the JSON in your iOS app remains the same as before. You can use URLSession and a JSON parsing library like Codable or a third-party library.

    By using Liquid templating, you can generate a JSON API with 11ty that meets your needs, and then consume it in your iOS app.

  5. User

    I get this error: Cannot GET /api/posts.json

  6. Meta Assistant

    The "Cannot GET /api/posts.json" error typically indicates that the file is not being generated or is not being served by your 11ty site.

    Here are a few things to check:

    1. File Name and Extension: Ensure that your Liquid template file is named correctly, e.g., posts.json.liquid. The .liquid extension is required for 11ty to recognize it as a Liquid template.

    2. Front Matter: Verify that the front matter in your posts.json.liquid file is correct. The permalink should be set to /api/posts.json, and the layout should reference the correct Liquid template.

    ---
    permalink: "/api/posts.json"
    layout: "posts.json.liquid"
    eleventyExcludeFromCollections: true
    ---
    
    1. Template Location: Make sure that your posts.json.liquid template is in the correct location. If it's in the _includes directory, you should reference it as layout: "_includes/posts.json.liquid".
    ---
    permalink: "/api/posts.json"
    layout: "_includes/posts.json.liquid"
    eleventyExcludeFromCollections: true
    ---
    
    1. 11ty Configuration: Check your .eleventy.js configuration file to ensure that Liquid templating is enabled. You should have a line like this:
    module.exports = function(eleventyConfig) {
      // ...
      return {
        templateFormats: ["md", "njk", "html", "liquid"],
        // ...
      };
    };
    
    1. Build and Serve: After making any changes, rebuild and reserver your 11ty site. If you're using the 11ty CLI, you can do this by running npx @11ty/eleventy --serve or npx @11ty/eleventy --watch.

    2. Check the Output Directory: Verify that the posts.json file is being generated in the correct output directory (usually _site). You can do this by checking the file system or by running npx @11ty/eleventy to build the site without serving it.

    If none of these steps resolve the issue, try checking the 11ty documentation or searching for similar issues on GitHub or other forums.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.