liquid-rails icon indicating copy to clipboard operation
liquid-rails copied to clipboard

How to call filters with more than 2 arguments

Open sdilshod opened this issue 6 years ago • 6 comments

Hello!

In rails i can write link_to 'this is a link', root_url, :class => 'css-class'

My question is how can i call link_to filter inside liquid template?

Thanks

sdilshod avatar Jun 26 '18 13:06 sdilshod

With static url we can write:

{{ 'link name' | link_to: 'root_url', class: 'css-class', title: 'link title' }}

but how about named routes (object routes) i don't know

sdilshod avatar Jun 26 '18 14:06 sdilshod

Hi @sdilshod,

Assume that I have a resource called articles In config/routes.rb

Rails.application.routes.draw do
resources :articles
end

Then in liquid template:

{{ 'link name' | link_to: request.articles_path, class: 'css-class', title: 'link title' }}

and the request object, come from somewhere in your controller: app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  def liquid_assigns
    {
      'request' => request_drop
    }
  end

  private

  def request_drop
    @request_drop ||= Liquid::RequestDrop.new
  end
end

Create new file : app/drops/liquid/request_drop.rb

module Liquid
  class RequestDrop < ::Liquid::Rails::Drop
    def initialize
    end
    def articles_path
      url_helpers.articles_path
    end
    private
    def url_helpers
      ::Rails.application.routes.url_helpers
    end
  end
end

Hope this help!

radinreth avatar Jun 27 '18 15:06 radinreth

Sample code available here.

radinreth avatar Jun 27 '18 15:06 radinreth

Thank you @radin-reth ! I made something like this for routes without additional params.

Can you show example for route helpers with params? Is it possible for example edit_article_path(@article)?

Now i have for this type routes corresponding methods inside drop class, but its little uncomfortably.

class CustomerDrop < Liquid::Rails::Drop
  attributes :id

  include Rails.application.routes.url_helpers

  def initialize(customer)
    @object = customer
  end

  def get_dashboard_customer_path
    return dashboard_customer_path(@object)
  end
end

sdilshod avatar Jun 28 '18 06:06 sdilshod

It's a bit tricky @sdilshod , I could not find a way to do it beside build a url by hand like what you already to, because liquid template accept only drop object and filter, and NOT ACCEPT any parameter. Please check it out: https://github.com/radin-reth/liquid-test/commit/55e98b0430eec8786e8e47532cf177a69fcd0ee7

Hope it helps!

radinreth avatar Jun 28 '18 15:06 radinreth

ок, thank you @radin-reth

sdilshod avatar Jun 29 '18 06:06 sdilshod