Ruby on rails 输出变细

Ruby on rails 输出变细,ruby-on-rails,slim-lang,Ruby On Rails,Slim Lang,我正在使用Base64.encode64(val)将html转换为Base64。 例如: 但如何将slim标记转换为变量?像这样: .class = link_to 'Link', link_path # <- this output with slim div 有一种方法是将slim代码放入partial并执行以下操作: - var = render 'partial' = Base64.encode64(var) # Convert into base64 如何做到这一点而不使用部

我正在使用
Base64.encode64(val)
将html转换为Base64。 例如:

但如何将slim标记转换为变量?像这样:

.class = link_to 'Link', link_path # <- this output with slim div
有一种方法是将slim代码放入partial并执行以下操作:

- var = render 'partial'
= Base64.encode64(var) # Convert into base64
如何做到这一点而不使用部分?

Slim,就像这样:

# Render a template file:
Slim::Template.new("template.slim", options).render(scope)

# Render a string:
Slim::Template.new(options) { "b slim markup" }.render(scope)
其中,options是slim的可选哈希,scope是执行模板代码的对象

因此,以下是:

slim_markup = <<-SLIM
  div
  span
  .another_div
SLIM

# The options hash and scope have been omitted for the sake of simplicity
html_output = Slim::Template.new { slim_markup }.render

但对于url帮助程序链接路径的示例,必须提供url帮助程序可用的作用域,例如控制器。

另一种方法是使用
capture
方法。从文档中:

使用绑定,您可以捕获局部变量,如下所示:

module Helpers
  def capture_to_local(var, &block)
    set_var = block.binding.eval("lambda {|x| #{var} = x }")
    # In Rails we have to use capture!
    # If we are using Slim without a framework (Plain Tilt),
    # you can just yield to get the captured block.
    set_var.call(defined?(::Rails) ? capture(&block) : yield)
  end
end
然后可以在Slim模板中使用辅助对象,如下所示

/ The captured_content variable must be known by the Binding beforehand.
= capture_to_local captured_content=:captured_content
  p This will be captured in the variable captured_content
= captured_content

阅读更多内容这是一个老问题,但我已经想了很多次了,我总是花很多时间研究它

使用Slim 4,您可以直接使用
capture

-val=捕获
div
跨度
.另一个部门

这会将渲染的slim放入变量。

您试图渲染包含slim标记的字符串而不是文件,对吗?@wolfemm render to var,是的。
<div></div>
<span></span>
<div class="another_div"></div>
module Helpers
  def capture_to_local(var, &block)
    set_var = block.binding.eval("lambda {|x| #{var} = x }")
    # In Rails we have to use capture!
    # If we are using Slim without a framework (Plain Tilt),
    # you can just yield to get the captured block.
    set_var.call(defined?(::Rails) ? capture(&block) : yield)
  end
end
/ The captured_content variable must be known by the Binding beforehand.
= capture_to_local captured_content=:captured_content
  p This will be captured in the variable captured_content
= captured_content