Sha256: e3c2f6cf57c2c98b698d4e625c9e2b6777438e1c2e7cab67215c997b328a5a76

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

require 'liquid'

class Asset < Liquid::Tag
  # Adds an `asset` tag to liquid. Usage:
  #
  # {% asset "path/to/asset.png" %}
  #
  # This will replace the tag with a relative path to the asset from the
  # current template. Using normal tags will work from the root, but when
  # building dynamic pages or reusing layouts, asset paths are dynamic and
  # will need to be rewritten.

  prepend Liquid::Tag::Disableable

  SYNTAX = /(#{Liquid::QuotedFragment}+)/o.freeze

  def initialize(tag_name, markup, tokens)
    super
    raise AssetError, 'Invalid layout syntax' unless markup =~ SYNTAX

    @path = parse_expression(Regexp.last_match(1))
    # This is defaulted to the pages dir, because it represents the structure
    # of our website. Asset directories are copied as siblings at runtime.
    @@root_dir ||= File.join(Dir.pwd, 'pages')
  end

  def self.root_dir=(dir)
    @@root_dir = dir
  end

  def render_to_output_buffer(context, output)
    unless @@root_dir
      raise AssetError,
            'root_dir must be set on Archival::Asset'
    end

    unless context.key? 'template_path'
      raise AssetError,
            'template_path must be provided to parse when using assets'
    end
    template_path = File.dirname(context['template_path'])
    abs_asset_path = Pathname.new(File.join(@@root_dir, @path))
    output << abs_asset_path.relative_path_from(template_path).to_s
    output
  end
end

class AssetError < Liquid::Error
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
archival-0.0.8 lib/tags/asset.rb