Sinatra 渲染 .md.erb 模板,如果存在,否则为 .md
Sinatra rendering .md.erb templates, if present, otherwise .md
使用 sinatra,我可以告诉它呈现降价模板,例如view/my_template.md 像这样传递模板名称:markdown :my_template
.
但是我想先通过erb处理,所以我的文件叫view/my_template.md.erb
但是...我也希望我的代码能够以任何一种方式工作。我希望它使用 .md.erb 文件(如果存在),否则使用 .md 文件。
我想知道在 sinatra 中是否有一种标准的方法可以做到这一点,而不是自己编写这个回退的逻辑。以下工作,但似乎不够优雅:
get '/route/to/my/page' do
begin
# Try to do erb processing into a string with the file view/my_template.md.erb
md_content = erb :my_template.md, :layout => false
rescue Errno::ENOENT
# Set it to use the view/my_template.md file instead
md_template = :my_template
end
# Either way we do the markdown rendering and use the erb layouts
markdown md_content || md_template, :layout_engine => :erb, :renderer => MARKDOWN_RENDERER
end
救援Errno::ENOENT 似乎不够优雅。代码也很混乱,我用“.md”指定了一个名称,以便它获取“.md.erb”文件。
我不认为存在任何类型的自动检测模板,也没有 'standard' 方法来执行您想要的操作。 Sinatra 的渲染方法,如 markown
或 erb
只是一堆围绕更通用的 render
方法的单行包装器,它只做它的名字所说的。
对于您的情况,手动检测首选模板及其类型应该很简单,不需要抛出异常。
get '/route/to/my/page' do
tpl_path = Dir.glob('views/my_template.md{,.erb}').sort.last
tpl_name = File.basename(tpl_path, '.*').to_sym
tpl_type = File.extname(tpl_path)
erb_output = erb(tpl_name) if tpl_type == '.erb'
markdown(erb_output || tpl_name)
end
Dir.glob
将选择 my_template.md.erb
而不是 my_template.md
。此外,使用 tpl_type
可以避免混淆原始模板类型。
使用 sinatra,我可以告诉它呈现降价模板,例如view/my_template.md 像这样传递模板名称:markdown :my_template
.
但是我想先通过erb处理,所以我的文件叫view/my_template.md.erb
但是...我也希望我的代码能够以任何一种方式工作。我希望它使用 .md.erb 文件(如果存在),否则使用 .md 文件。
我想知道在 sinatra 中是否有一种标准的方法可以做到这一点,而不是自己编写这个回退的逻辑。以下工作,但似乎不够优雅:
get '/route/to/my/page' do
begin
# Try to do erb processing into a string with the file view/my_template.md.erb
md_content = erb :my_template.md, :layout => false
rescue Errno::ENOENT
# Set it to use the view/my_template.md file instead
md_template = :my_template
end
# Either way we do the markdown rendering and use the erb layouts
markdown md_content || md_template, :layout_engine => :erb, :renderer => MARKDOWN_RENDERER
end
救援Errno::ENOENT 似乎不够优雅。代码也很混乱,我用“.md”指定了一个名称,以便它获取“.md.erb”文件。
我不认为存在任何类型的自动检测模板,也没有 'standard' 方法来执行您想要的操作。 Sinatra 的渲染方法,如 markown
或 erb
只是一堆围绕更通用的 render
方法的单行包装器,它只做它的名字所说的。
对于您的情况,手动检测首选模板及其类型应该很简单,不需要抛出异常。
get '/route/to/my/page' do
tpl_path = Dir.glob('views/my_template.md{,.erb}').sort.last
tpl_name = File.basename(tpl_path, '.*').to_sym
tpl_type = File.extname(tpl_path)
erb_output = erb(tpl_name) if tpl_type == '.erb'
markdown(erb_output || tpl_name)
end
Dir.glob
将选择 my_template.md.erb
而不是 my_template.md
。此外,使用 tpl_type
可以避免混淆原始模板类型。