سؤال

I am coding a custom Liquid tag as Jekyll plugin for which I need to preserve some values until the next invocation of the tag within the current run of the jekyll build command.

Is there some global location/namespace that I could use to store and retrieve values (preferably key-value pairs / a hash)?

هل كانت مفيدة؟

المحلول

You could add a module with class variables for storing the persistent values, then include the module in your tag class. You would need the proper accessors depending on the type of the variables and the assignments you might want to make. Here's a trivial example implementing a simple counter that keeps track of the number of times the tag was called in DataToKeep::my_val:

module DataToKeep
  @@my_val = 0

  def my_val
    @@my_val
  end

  def my_val= val
    @@my_val = val
  end
end

module Jekyll
  class TagWithKeptData < Liquid::Tag
    include DataToKeep

    def render(context)
      self.my_val = self.my_val + 1
      return "<p>Times called: #{self.my_val}</p>"
    end
  end
end

Liquid::Template.register_tag('counter', Jekyll::TagWithKeptData)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top