Rails - Mix erb tags with markdown

♀尐吖头ヾ 提交于 2020-01-25 11:00:26

问题


I want the users on my blogsite to be able to type in markdown text in a textarea to make a blogpost. This markdown text would then be converted with a tool like Redcarpet or kramdown. Now I also want the user to be able to call a partial view that lays out some pictures. So in other words, I want the user to be able to type in the following code anywhere in between his markdown text (and it being interpreted as erb code)

<%= render partial: "slider", locals: {imgs: ["image1.jpg", "image2.jpg"]} %>

Is this possible somehow? kramdown allows you to use block-level HTML tags (div, p, pre, …), so maybe this could be used to some advantage?


回答1:


Do you really want your customers to be able to write ERB? That's extremely dangerous, they can use any Ruby function in ERB, including Kernel functionalities. What about allowing a simple templating system, either a custom one or an existing one. For example you can use Liquid (from Shopify), provide some custom tags so they won't need all the boilerplate but just something like {% dosomething 'partial', 'img1', 'img2' %}, then you first convert liquid into normal text, then you convert markdown to html, cache it and display that to the user. An example:

# get your customer text from somewhere, like params[:markdown_text]
template = params[:markdown_text]
markdown = Liquid::Template.parse(template).render
html_text = Redcarpet::Markdown.new(renderer, extensions = {}).render(markdown)

puts html_text.to_s # => text with html tags, ensure to use `html_safe` on it in views

And you have your text ready



来源:https://stackoverflow.com/questions/31994483/rails-mix-erb-tags-with-markdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!