DEV Community

Jeremy Woertink
Jeremy Woertink

Posted on

Plain text pages in Lucky

Sometimes you may need to render a page that's not a webpage with HTML, but more just plain text. One example would be a robots.txt. Now, what you may be thinking right now is "why not just make a static text file, and throw that in your public directory?". Well, you'd be right, but then I wouldn't have a reason to write this post πŸ˜›. Another reason (which I'll show you) is for some dynamic content.

First we will make a new action in src/actions/static_pages/robots.cr

class StaticPages::Robots < BrowserAction
  get "/robots.txt" do
    text <<-TEXT
    User-Agent: *
    TEXT
  end
end
Enter fullscreen mode Exit fullscreen mode

That's it! Boot your server up, and check out your localhost:3000/robots.txt and check out the content type is set to text/plain like it should be.

With Lucky, there's a helper method called text. This is a replacement to a redirect or render for your action which means you only call it once. It's not chainable, so if you have a lot of text to render, you can break it out in to methods, and then do something like text my_formatted_output.

Now, I did mention that you may want to go with this route if you're doing something dynamic. Let's say you have a multi-tenant app where multiple domains point to your single app. Having one robots.txt file in your public directory might not work. Each domain might have different requirements.

class StaticPages::Robots < BrowserAction
  get "/robots.txt" do
    text <<-TEXT
    Sitemap: https://#{current_site.host}/sitemap.xml
    User-Agent: *
    TEXT
  end
end
Enter fullscreen mode Exit fullscreen mode

See? It's useful, now go and use it!

Top comments (0)