Rails - Render different layouts based on view template engine

51 Views Asked by At

I'm using the HighVoltage gem to render static pages in my Rails app. There are a few different sections rendered from static pages, for example blog posts and support articles. Currently everything is rendered using ERB, however I want to start using Markdown for the blog posts. Some of the support articles have interactive components with JavaScript so I'd like to continue to use ERB for them, rather than convert everything to Markdown.

I added this MarkdownTemplateHandler which renders Markdown automatically if I create a .html.md view. However the Markdown is just the raw post content with the standard layout, I need to add some wrapper elements around it. A different layout for Markdown blog posts would be ideal. The HighVoltage gem exposes a way to override the rendering, and suggests a layout_for_page method to select which layout can be used.

What I cannot figure out is how to identify which view template engine will be used in the controller, or even the file name of the view that will be rendered. I'd also like to add support for frontmatter in Markdown files, so again I will need to figure out if it's a .html.erb or .html.md file and only parse the later.

1

There are 1 best solutions below

0
Alex On

You'd have to find the template first so you can decide on the layout:

class PagesController < ApplicationController
  include HighVoltage::StaticPage

  layout ->() {
    template = lookup_context.find(current_page)
    extname  = Pathname.new(template.identifier).extname

    case extname
    when ".md"
      "markdown"
    when ".erb"
      "application"
    end
  }
end