如何在Rails 3中使用Markdown自动渲染局部图片? [英] How can I automatically render partials using markdown in Rails 3?

查看:79
本文介绍了如何在Rails 3中使用Markdown自动渲染局部图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的部分内容作为降价片段.使用标准rails erb模板渲染它们的最简单方法是什么?

I want to have some of my partials as markdown snippets. What is the easiest way to render them using the standard rails erb templating?

理想情况下,我想执行以下操作:

Ideally, I'd like to do something like this:

如果我在 app/views/_my_partial.md.erb 中有部分内容:

If I have a partial in app/views/_my_partial.md.erb:

My awesome view
===============

Look, I can **use** <%= language %>!

我是从这样的观点引用的:

which I reference from a view like so:

<%= render "my_partial", :language => "Markdown!" %>

我想获得如下所示的输出:

I want to get output that looks like this:

<h1>My awesome view</h1>
<p>Look, I can <strong>use</strong> Markdown!</p>

推荐答案

结果证明,正确的方法(tm)使用的是ActionView::Template.register_template_handler:

Turns out, the Right Way (tm) to do this is using ActionView::Template.register_template_handler:

lib/markdown_handler.rb :

require 'rdiscount'

module MarkdownHandler
  def self.erb
    @erb ||= ActionView::Template.registered_template_handler(:erb)
  end

  def self.call(template)
    compiled_source = erb.call(template)
    "RDiscount.new(begin;#{compiled_source};end).to_html"
  end
end

ActionView::Template.register_template_handler :md, MarkdownHandler

如果您在config/application.rb(或初始化程序)中使用require 'markdown_handler',则可以使用扩展名.html.md通过ERb插值将任何视图或部分视图呈现为Markdown:

If you require 'markdown_handler' in your config/application.rb (or an initializer), then any view or partial can be rendered as Markdown with ERb interpolation using the extension .html.md:

app/views/home/index.html.md :

My awesome view
===============

Look, I can **use** <%= @language %>!

app/controllers/home_controller.rb :

class HomeController < ApplicationController
  def index
    @language = "Markdown"
  end
end

这篇关于如何在Rails 3中使用Markdown自动渲染局部图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆