Skip to content

Instantly share code, notes, and snippets.

@msievers
Created November 20, 2014 11:11
Show Gist options
  • Save msievers/424ec4fd684f6d4540f7 to your computer and use it in GitHub Desktop.
Save msievers/424ec4fd684f6d4540f7 to your computer and use it in GitHub Desktop.
Render templates only if they exist (with fallback option)
module ApplicationHelper
# https://coderwall.com/p/ftbmsa (Render template if exists in Rails)
def try_to_render(partial_path, options = {})
fallback = options.delete(:fallback_to)
prefixes = partial_path.split("/")[0..-2].presence || controller._prefixes
partial_name = partial_path.split("/").last
if lookup_context.exists?(partial_name, prefixes, true) # "true" is crucial !
render partial_path, options
else
render fallback, options
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment