【问题标题】:Passing rails objects or variables to liquid将轨道对象或变量传递给液体
【发布时间】:2020-09-22 19:13:20
【问题描述】:

我为 shopify 编写了一个按设计工作的应用程序。现在我想添加应用代理以使内容嵌入到商店中。代理工作正常,但 shopify 期望响应(在我的情况下是视图)作为纯液体。 ruby 中的原始视图有一些使用多个变量和对象的逻辑。

我安装了液体宝石。我浏览的教程似乎有点过时了。

@template = Liquid::Template.parse("hi {{name}}")  # Parses and compiles the template
@template.render( 'name' => 'tobi' )               # Renders the output 
=> "hi tobi"

这是有效的,但它只适用于字符串。我看了railscast,我认为这将是一种让液体进入物体的简单方法。但它又过时了,“liquid_methods”不再起作用。

所以我在我的模型中编写了自己的方法:

  def to_liquid
    { "title" => self.title,
      "description" => self.description
    } 

如果我尝试在控制台中使用我的方法渲染它,如下所示:

@template = Liquid::Template.parse("Welcome to {{object.title}}")
@template.render(object.title.to_liquid)

我收到以下错误:

Liquid::ArgumentError (Liquid error: Expected Hash or Liquid::Context as parameter)

现在我卡住了...

用液体访问 RoR 对象的最简单方法是什么?

【问题讨论】:

    标签: ruby-on-rails liquid


    【解决方案1】:

    在尝试了几乎所有可能的方法来传递变量之后,这成功了:

    @object = Object.find(params[:id])
    @hash_object = @object.to_liquid
    
    @template = Liquid::Template.parse("Welcome to {{object_title}}")
    @template.render('object_title' => @hash_object["title"])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多