DEV Community

Jeremy Woertink
Jeremy Woertink

Posted on

5 1

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!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more