使用sinatra,我可以告诉它呈现一个标记模板,例如view/my_template.md,传递模板名如下:markdown :my_template。
但是我想先进行erb处理,所以我的文件名为view/my_template.md.erb。
但是..。我也希望我的代码能以任何方式工作。如果存在,我希望它使用.md.erb文件,但如果存在,则使用.md文件。
我想知道在辛纳屈是否有一种标准的方法,而不是自己编写这个退路的逻辑。以下内容很有效,但似乎不雅:
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’文件。
发布于 2018-06-25 20:18:04
我不认为有任何一种自动检测模板存在,也没有“标准”的方式来做你想要的。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)
endDir.glob将选择my_template.md.erb而不是my_template.md。此外,使用tpl_type可以避免对原始模板类型的混淆。
https://stackoverflow.com/questions/50742002
复制相似问题