Rails-混合带有Markdown的erb标签 [英] Rails - Mix erb tags with markdown
问题描述
我希望我博客站点上的用户能够在文本区域中输入markdown文本以撰写博客文章.然后,将使用诸如Redcarpet或kramdown之类的工具来转换此markdown文本.现在,我还希望用户能够调用布局一些图片的局部视图.因此,换句话说,我希望用户能够在其降价文本之间的任何地方键入以下代码(并将其解释为erb代码)
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"]} %>
这有可能吗? kramdown允许您使用块级HTML标记(div,p,pre,...),所以也许可以利用它来获得一些优势?
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?
推荐答案
您真的希望您的客户能够编写ERB吗?这是非常危险的,他们可以在ERB中使用任何Ruby函数,包括内核功能.允许使用简单的模板系统,既可以是自定义系统,也可以是现有系统.例如,您可以使用液体(来自Shopify),提供一些自定义标签,这样它们就不需要所有样板,而只需要类似于{% dosomething 'partial', 'img1', 'img2' %}
,然后您首先将液体转换为普通文本,然后将markdown转换为html,缓存,并将其显示给用户.例子:
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
您已经准备好文字
这篇关于Rails-混合带有Markdown的erb标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!