Sha256: 11d6bf9129ff9ee208787ad08486e0348bd129082c562dc545641e56fcf917ad

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

require "tilt"

class Tynn
  module Render
    def self.setup(app, options = {}) # :nodoc:
      app.set(:render, {
        layout: options.fetch(:layout, "layout"),
        views: options.fetch(:views, File.expand_path("views", Dir.pwd)),
        engine: options.fetch(:engine, "erb"),
        engine_opts: {
          escape_html: true
        }.merge(options.fetch(:options, {}))
      })
    end

    module InstanceMethods
      def render(template, locals = {}, layout = self.class.settings.dig(:render, :layout))
        res.headers[Rack::CONTENT_TYPE] ||= Syro::Response::DEFAULT

        res.write(view(template, locals, layout))
      end

      def view(template, locals = {}, layout = self.class.settings.dig(:render, :layout))
        partial(layout, locals.merge(content: partial(template, locals)))
      end

      def partial(template, locals = {})
        tilt(template_path(template), locals, self.class.settings.dig(:render, :engine_opts))
      end

      private

      def tilt(file, locals = {}, opts = {})
        tilt_cache.fetch(file) {
          Tilt.new(file, 1, opts)
        }.render(self, locals.merge(app: self))
      end

      def tilt_cache
        Thread.current[:tilt_cache] ||= Tilt::Cache.new
      end

      def template_path(template)
        dir = self.class.settings.dig(:render, :views)
        ext = self.class.settings.dig(:render, :engine)

        File.join(dir, "#{ template }.#{ ext }")
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tynn-2.0.0.alpha lib/tynn/render.rb