Last Updated: February 25, 2016
·
9.773K
· zinkkrysty

Render template if exists in Rails

Sometimes you have templates in your code that match records in the database. Maintaining and synchronizing them is very hard, but this tip helps you when you only need templates for some of the records.

It's a very simple trick, and I tend to use Google every time I need it, so why not put it here, maybe someone finds it useful:

<% if lookup_context.exists?(dynamic_template_name, ["path1/path2"], true) %>
   <%= render dynamic_template_name %>
<% end %>

The true argument means that it's a partial I'm looking for.

If dynamic_template_name is "template1", the code above matches this template:
path1/path2/_template1.html.erb (or haml, slim, etc) in any of your places where Rails will normally look for templates.

Here's the full reference to the function: http://apidock.com/rails/ActionView/LookupContext/ViewPaths/exists%3F

This helped me: http://stackoverflow.com/questions/3559419/is-there-any-rails-function-to-check-if-a-partial-exists

Note: Of course I'm not advocating for consistent use of templates that match database records. That's a bad idea. But for very simple things (I have like 6 records in mine and I know they will rarely change) it's nice to use this trick.

1 Response
Add your response

Thanks for the tip! I needed a way to render dynamic template names - not partials. It took me a while to understand, that you need to turn the true in the call to a false (or skip it altogether) to look up a template.

If the templates/partials exist in the conventional namespace, you can even simplify the call this way:

lookup_context.exists?(dynamic_template_name, _prefixes)

_prefixes will return the context of the controller's inheritance chain.

Kudos for the details to Flackou, http://stackoverflow.com/a/16999991/214702

over 1 year ago ·