loading...

Plain text pages in Lucky

jwoertink profile image Jeremy Woertink ใƒป2 min read

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

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

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

Posted on by:

jwoertink profile

Jeremy Woertink

@jwoertink

Software Dev in Las Vegas. CTO for Namechk.com. I work for another company too. I also teach programming for UNLV

Discussion

markdown guide