pax_global_header00006660000000000000000000000064151302176510014513gustar00rootroot0000000000000052 comment=2b1189faba686df872d8d9838c9d482e7c24ea19 tilt-2.7.0/000077500000000000000000000000001513021765100124755ustar00rootroot00000000000000tilt-2.7.0/.autotest000066400000000000000000000005301513021765100143440ustar00rootroot00000000000000require 'rubygems' require 'bacon' require 'autotest/bacon' class Autotest::Bacon < Autotest undef make_test_cmd def make_test_cmd(files_to_test) args = files_to_test.keys.flatten.join(' ') args = '-a' if args.empty? # TODO : make regex to pass to -n using values "#{ruby} -S bacon -I#{libs} -o TestUnit #{args}" end end tilt-2.7.0/.ci.gemfile000066400000000000000000000031331513021765100145000ustar00rootroot00000000000000source 'https://rubygems.org' gem 'rake' gem 'minitest' gem 'babel-transpiler' gem 'erubi' gem 'liquid' gem 'livescript' gem 'nokogiri' gem 'pdf-reader' gem 'prawn', '>= 2.0.0' gem 'radius' gem 'slim' gem 'typescript-node' gem 'pandoc-ruby' if RUBY_VERSION >= '3.3' gem 'csv' # liquid dependency gem 'base64' end if RUBY_VERSION >= '3.4' # asciidoc dependency gem 'logger' end if RUBY_VERSION < '2.6' gem 'rdoc', '< 6.4' else gem 'rdoc' end gem 'coffee-script' if ENV['COFFEE_SCRIPT'] if RUBY_VERSION < '2.3' gem 'execjs', '< 2.9' end if RUBY_VERSION < '2.7' gem 'markaby', '< 0.9.1' gem 'builder', '< 3.3.0' else gem 'markaby' gem 'builder' end if RUBY_VERSION < '2.1' gem 'kramdown', '< 1.1' else gem 'asciidoctor' gem 'kramdown' end if RUBY_ENGINE == 'jruby' gem 'jar-dependencies', '0.4.1' end if RUBY_ENGINE == 'jruby' gem 'haml', '< 6' else gem 'haml', '>= 4' end if RUBY_VERSION >= '3.2' gem 'sass-embedded' elsif RUBY_VERSION >= '3.1' gem 'sass-embedded', '< 1.70' elsif RUBY_ENGINE == 'jruby' gem 'sass' else gem 'sassc' end if RUBY_VERSION >= '3.1' # Was default library, now bundled gem. # Needed by prawn tests. gem 'matrix' end platform :ruby do gem 'RedCloth' gem 'commonmarker' gem 'yajl-ruby' gem 'rdiscount', '>= 2.1.6' if RUBY_VERSION < '2.1' gem 'redcarpet', '< 3.6.1' else gem 'redcarpet' end if RUBY_VERSION < '2.3' # CommonMarker versions that support Ruby <2.3 have # a dependency on ruby-enum, which requires Ruby 2.3 # without specifying required_ruby_version gem 'ruby-enum', '< 0.6' end end tilt-2.7.0/.github/000077500000000000000000000000001513021765100140355ustar00rootroot00000000000000tilt-2.7.0/.github/workflows/000077500000000000000000000000001513021765100160725ustar00rootroot00000000000000tilt-2.7.0/.github/workflows/ci.yml000066400000000000000000000014221513021765100172070ustar00rootroot00000000000000name: CI on: push: branches: [ master ] pull_request: branches: [ master ] permissions: contents: read jobs: test: strategy: fail-fast: false matrix: os: [ubuntu-latest] ruby: [ "2.0.0", 2.1, 2.3, 2.4, 2.5, 2.6, 2.7, "3.0", 3.1, 3.2, 3.3, 3.4, "4.0", jruby-10.0 ] include: - { os: ubuntu-22.04, ruby: jruby-9.2 } runs-on: ${{ matrix.os }} name: ${{ matrix.ruby }} env: BUNDLE_GEMFILE: .ci.gemfile COFFEE_SCRIPT: use steps: - uses: actions/checkout@v4 # Pandoc needs Pandoc - run: sudo apt-get install -y pandoc - uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} bundler-cache: true cache-version: 1 - run: bundle exec rake tilt-2.7.0/.gitignore000066400000000000000000000001161513021765100144630ustar00rootroot00000000000000/dist *.swp /vendor /.bundle /.yardoc /rdoc .sass-cache /tilt-*.gem /coverage tilt-2.7.0/CHANGELOG.md000066400000000000000000000245301513021765100143120ustar00rootroot00000000000000## 2.7.0 (2026-01-09) * Support passing template-specific options to Tilt::Pipeline.new (LevitatingBusinessMan) (#24) * Remove deprecated creole template (jeremyevans) * Make the rendering of Prawn templates idempotent (rickenharp) (#20) ## 2.6.1 (2025-07-07) * Fix race condition during parallel coverage testing using Template compiled_path option/method (jeremyevans) ## 2.6.0 (2025-01-13) * Support :compiled_path option, needed for compiled paths when using :scope_class and fixed locals (jeremyevans) * Support :scope_class option to force a specific scope class, instead of using the class of the provided scope (jeremyevans) * Support fallback fixed locals for templates without extracted locals via :default_fixed_locals option (jeremyevans) * Add Tilt.extract_fixed_locals accessor for enabling :extract_fixed_locals globally (jeremyevans) * Support embedded fixed locals for templates via magic comments via :extract_fixed_locals option (jeremyevans) * Support fixed locals for templates via :fixed_locals option (jeremyevans) ## 2.5.0 (2024-12-20) * Deprecate creole templates as they require modifying frozen string literals (jeremyevans) * Remove deprecated erubis, wikicloth, and maruku templates (jeremyevans) * Avoid spurious frozen string literal warnings for chilled strings when using Ruby 3.4 (jeremyevans) ## 2.4.0 (2024-06-27) * Support commonmarker 1.0+ API (unasuke) (#10) * Make etanni template work with frozen string literals (jeremyevans) * Deprecate erubis, wikicloth, and maruku templates as they require modifying frozen string literals (jeremyevans) * Make SassTemplate ignore unsupported options when using sass-embedded (jeremyevans) ## 2.3.0 (2023-09-14) * Remove deprecated support for non-string template code in PrawnTemplate (jeremyevans) * Remove deprecated support for {ERB,Erubis}Template#default_output_variable{,=} (jeremyevans) * Remove deprecated support for CoffeeScriptTemplate.default_no_wrap{,=} (jeremyevans) * Remove deprecated support for RedCarpet 1.x (jeremyevans) * Remove deprecated support for Tilt.current_template (jeremyevans) * Make Template#freeze_string_literals? work correctly with Template#compiled_path (jeremyevans) * Support :freeze option for StringTemplate to support frozen string literals (jeremyevans) * Make Tilt.finalize! a no-op if it has already been called (jeremyevans) ## 2.2.0 (2023-06-05) * Remove deprecated BlueCloth, Less, and Sigil support (jeremyevans) * Drop support for RDoc < 4 (jeremyevans) * Deprecate Tilt::Cache (jeremyevans) * Deprecate Tilt.current_template (jeremyevans) * Deprecate support for RedCarpet 1.x (jeremyevans) * Deprecate CoffeeScriptTemplate.default_no_wrap{,=} aliases of default_bare{,=} (jeremyevans) * Deprecate {ERB,Erubis}Template#default_output_variable{,=} (jeremyevans) * Deprecate non-string template code in PrawnTemplate (jeremyevans) * Deprecate default lazy loading of handlebars/org/emacs_org/jbuilder external template engines (jeremyevans) * Handle `locals` as a local variable in templates (timriley) (#3) * Do not cache output in PrawnTemplate#evaluate (jeremyevans) * Do not mark PrawnTemplate as not allowing script, since it can be used to execute arbitrary Ruby code (jeremyevans) * Remove Redcarpet1Template and Redcarpet2Template from the RedCarpet support (jeremyevans) * Separate CoffeeScriptTemplate.default_bare and CoffeeScriptLiterateTemplate.default_bare (jeremyevans) * Fix possible issue in KramdownTemplate under concurrent use (jeremyevans) * Do not define yield tag for RadiusTemplate if no block is given to render (jeremyevans) * Avoid holding mutex while compiling template methods (jeremyevans) * Template#prepare no longer needs to be overridden if no preparation work is needed (jeremyevans) * Fix potential concurrency issues in Mapping (jeremyevans) * Stop modifying given locals hash in tilt/prawn (jeremyevans) * Change visibility of Template#compiled_method to public (jeremyevans) * Add Tilt::StaticTemplate for templates that return the same output for every render (jeremyevans) * Add Tilt::Mapping#finalized and Tilt.finalize! for finalized mappings that do not require mutex synchronization (jeremyevans) * Add frozen_string_literal magic comment to all source files (jeremyevans) * Support templates with frozen compiled source code (jeremyevans) * Support :skip_compiled_encoding_detection template option to not scan compiled source code for encoding lines (jeremyevans) * Ship slim template support with tilt (minad) (#4) * Template#extract_{encoding,magic_comment} private methods now require a block (jeremyevans) The repository switched to https://github.com/jeremyevans/tilt, so issue references above are for that repository, and issue references below are for the previous repository (https://github.com/rtomayko/tilt). ## 2.1.0 (2023-02-17) * Use UnboundMethod#bind_call on Ruby 2.7+ for better performance (#380, jeremyevans) * Add Tilt::Template#freeze_string_literals? for freezing string literals in compiled templates (#301, jeremyevans) * Use Haml::Template for Tilt::HamlTemplate if available (Haml 6+) (#391, ntkme) * Deprecate BlueCloth, Less, and Sigil support (#382, jeremyevans) * Add Template#compiled_path accessor to save compiled template output to file (#369, jeremyevans) * Add Mapping#unregister to remove registered extensions (#376, jeremyevans) * Add Mapping#register_pipeline to register template pipelines (#259, jeremyevans) * Remove Tilt::Dummy (#364, jeremyevans) * Ensure Mapping#extensions\_for returns unique values (#342, mojavelinux) * Remove opal support, since the the opal API changed (#374, jeremyevans) * Remove .livescript extension for LiveScript (#374, jeremyevans) * Set required\_ruby\_version in gemspec (#371, jeremyevans) ## 2.0.11 (2022-07-22) * Fix #extensions\_for for RedcarpetTemplate (judofyr) * Support the new sass-embedded gem (#367, ntkme) * Add Tilt::EmacsOrg support (#366, hacktivista) * Improve rendering of BasicObject instances (#348, jeremyevans) * Fix Ruby 3.0 compatibility (#360, voxik) ## 2.0.10 (2019-09-23) * Remove test files from bundled gem (#339, greysteil) * Fix warning when using yield in templates on ruby 2.7 (#343, jeremyevans) ## 2.0.9 (2018-11-28) * Use new ERB API in Ruby 2.6 (#329, koic) * Support the new sassc gem (#336, jdickey, judofyr) ## 2.0.8 (2017-07-24) * Register .tsx for TypeScript (#315, backus) * Use Haml 5's new API (#312, k0kubun) * Use correct parser options for CommonMarker (#320, rewritten) * Suppress warnings when no locals are used (#304, amatsuda) * Haml: Accept `outvar` (#317, k0kubun) ## 2.0.7 (2017-03-19) * Do not modify BasicObject during template compilation on ruby 2.0+ (#309, jeremyevans) ## 2.0.6 (2017-01-26) * Add support for LiveScript (#286, @Announcement Jacob Francis Powers) * Add support for Sigil (#302, winebarrel) * Add support for Erubi (#308, jeremyevans) * Add support for options in Liquid (#298, #299, laCour) * Always sort locals by strings (#307, jeremyevans) * Fix test warnings (#305, amatsuda) * Fix indentation (#293, yui-knk) * Use SVG badges in README (#294, vasinov) * Fix typo and trailing space (#295, #296, karloescota) ## 2.0.5 (2016-06-02) * Add support for reST using Pandoc (#284, mfenner) * Make lazy loading thread-safe; remove warning (judofyr) ## 2.0.4 (2016-05-16) * Fix regression in BuilderTemplate (#283, judofyr) ## 2.0.3 (2016-05-12) * Add Pandoc support (#276, jmuheim) * Add CommonMark support (#282, raphink) * Add TypeScript support (#278, nghitran) * Work with frozen string literal (#274, jeremyevans) * Add MIME type for Babel (#273, SaitoWu) ## 2.0.2 (2016-01-06) * Pass options to Redcarpet (#250, hughbien) * Haml: Improve error message on frozen self (judofyr) * Add basic support for Babel (judofyr) * Add support for .litcoffee (#243, judofyr, mr-vinn) * Document Tilt::Cache (#266, tommay) * Sort local keys for better caching (#257, jeremyevans) * Add more CSV options (#256, Juanmcuello) * Add Prawn template (kematzy) * Improve cache-miss performance in Tilt::Cache (#251, tommay) * Add man page (#241, josephholsten) * Support YAML/JSON data in bin/tilt (#241, josephholsten) ## 2.0.1 (2014-03-21) * Fix Tilt::Mapping bug in Ruby 2.1.0 (9589652c569760298f2647f7a0f9ed4f85129f20) * Fix `tilt --list` (#223, Achrome) * Fix circular require (#221, amarshall) ## 2.0.0 (2013-11-30) * Support Pathname in Template#new (#219, kabturek) * Add Mapping#templates_for (judofyr) * Support old-style #register (judofyr) * Add Handlebars as external template engine (#204, judofyr, jimothyGator) * Add org-ruby as external template engine (#207, judofyr, minad) * Documentation typo (#208, elgalu) ## 2.0.0.beta1 (2013-07-16) * Documentation typo (#202, chip) * Use YARD for documentation (#189, judofyr) * Add Slim as an external template engine (judofyr) * Add Tilt.templates_for (#121, judofyr) * Add Tilt.current_template (#151, judofyr) * Avoid loading all files in tilt.rb (#160, #187, judofyr) * Implement lazily required templates classes (#178, #187, judofyr) * Move #allows_script and default_mime_type to metadata (#187, judofyr) * Introduce Tilt::Mapping (#187, judofyr) * Make template compilation thread-safe (#191, judofyr) ## 1.4.1 (2013-05-08) * Support Arrays in pre/postambles (#193, jbwiv) ## 1.4.0 (2013-05-01) * Better encoding support ## 1.3.7 (2013-04-09) * Erubis: Check for the correct constant (#183, mattwildig) * Don't fail when BasicObject is defined in 1.8 (#182, technobrat, judofyr) ## 1.3.6 (2013-03-17) * Accept Hash that implements #path as options (#180, lawso017) * Changed extension for CsvTemplate from '.csv' to '.rcsv' (#177, alexgb) ## 1.3.5 (2013-03-06) * Fixed extension for PlainTemplate (judofyr) * Improved local variables regexp (#174, razorinc) * Added CHANGELOG.md ## 1.3.4 (2013-02-28) * Support RDoc 4.0 (#168, judofyr) * Add mention of Org-Mode support (#165, aslakknutsen) * Add AsciiDoctorTemplate (#163, #164, aslakknutsen) * Add PlainTextTemplate (nathanaeljones) * Restrict locals to valid variable names (#158, thinkerbot) * ERB: Improve trim mode support (#156, ssimeonov) * Add CSVTemplate (#153, alexgb) * Remove special case for 1.9.1 (#147, guilleiguaran) * Add allows\_script? method to Template (#143, bhollis) * Default to using Redcarpet2 (#139, DAddYE) * Allow File/Tempfile as filenames (#134, jamesotron) * Add EtanniTemplate (#131, manveru) * Support RDoc 3.10 (#112, timfel) * Always compile templates; remove old source evaluator (rtomayko) * Less: Options are now being passed to the parser (#106, cowboyd) tilt-2.7.0/COPYING000066400000000000000000000021201513021765100135230ustar00rootroot00000000000000Copyright (c) 2010-2016 Ryan Tomayko Copyright (c) 2015-2023 Jeremy Evans Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. tilt-2.7.0/README.md000066400000000000000000000403261513021765100137610ustar00rootroot00000000000000Tilt ==== Tilt is a thin interface over a bunch of different Ruby template engines in an attempt to make their usage as generic as possible. This is useful for web frameworks, static site generators, and other systems that support multiple template engines but don't want to code for each of them individually. The following features are supported for all template engines (assuming the feature is relevant to the engine): * Custom template evaluation scopes / bindings * Ability to pass locals to template evaluation * Support for passing a block to template evaluation for `yield` * Backtraces with correct filenames and line numbers * Template file caching and reloading * Fast, method-based template source compilation The primary goal is to get all of the things listed above right for all template engines included in the distribution. Support for these template engines is included with Tilt: | Engine | File Extensions | Required Libraries | | --------------------------------------------------- | ----------------------- | ------------------------------ | | {Asciidoctor}[rdoc-ref:lib/tilt/asciidoc.rb] | .ad, .adoc, .asciidoc | asciidoctor | | {Babel}[rdoc-ref:lib/tilt/babel.rb] | .es6, .babel, .jsx | babel-transpiler | | {Builder}[rdoc-ref:lib/tilt/builder.rb] | .builder | builder | | {CoffeeScript}[rdoc-ref:lib/tilt/coffee.rb] | .coffee | coffee-script (+ javascript) | | {CoffeeScriptLiterate}[rdoc-ref:lib/tilt/coffee.rb] | .litcoffee | coffee-script (+ javascript) | | {CommonMarker}[rdoc-ref:lib/tilt/commonmarker.rb] | .markdown, .mkd, .md | commonmarker | | {CSV}[rdoc-ref:lib/tilt/csv.rb] | .rcsv | csv (ruby stdlib) | | {ERB}[rdoc-ref:lib/tilt/erb.rb] | .erb, .rhtml | erb (ruby stdlib) | | {Erubi}[rdoc-ref:lib/tilt/erubi.rb] | .erb, .rhtml, .erubi | erubi | | {Etanni}[rdoc-ref:lib/tilt/etanni.rb] | .ern, .etanni | none | | {Haml}[rdoc-ref:lib/tilt/haml.rb] | .haml | haml | | {Kramdown}[rdoc-ref:lib/tilt/kramdown.rb] | .markdown, .mkd, .md | kramdown | | {Liquid}[rdoc-ref:lib/tilt/liquid.rb] | .liquid | liquid | | {LiveScript}[rdoc-ref:lib/tilt/livescript.rb] | .ls | livescript (+ javascript) | | {Markaby}[rdoc-ref:lib/tilt/markaby.rb] | .mab | markaby | | {Nokogiri}[rdoc-ref:lib/tilt/nokogiri.rb] | .nokogiri | nokogiri | | {Pandoc}[rdoc-ref:lib/tilt/pandoc.rb] | .markdown, .mkd, .md | pandoc | | {Plain}[rdoc-ref:lib/tilt/plain.rb] | .html | none | | {Prawn}[rdoc-ref:lib/tilt/prawn.rb] | .prawn | prawn | | {Radius}[rdoc-ref:lib/tilt/radius.rb] | .radius | radius | | {RDiscount}[rdoc-ref:lib/tilt/rdiscount.rb] | .markdown, .mkd, .md | rdiscount | | {RDoc}[rdoc-ref:lib/tilt/rdoc.rb] | .rdoc | rdoc | | {Redcarpet}[rdoc-ref:lib/tilt/redcarpet.rb] | .markdown, .mkd, .md | redcarpet | | {RedCloth}[rdoc-ref:lib/tilt/redcloth.rb] | .textile | redcloth | | {RstPandoc}[rdoc-ref:lib/tilt/rst-pandoc.rb] | .rst | pandoc | | {Slim}[rdoc-ref:lib/tilt/slim.rb] | .slim | slim | | {Sass}[rdoc-ref:lib/tilt/sass.rb] | .sass | sass-embedded, sassc, or sass | | {Scss}[rdoc-ref:lib/tilt/sass.rb] | .scss | sass-embedded, sassc, or sass | | {String}[rdoc-ref:lib/tilt/string.rb] | .str | none | | {TypeScript}[rdoc-ref:lib/tilt/typescript.rb] | .ts | typescript (+ javascript) | | {Yajl}[rdoc-ref:lib/tilt/yajl.rb] | .yajl | yajl-ruby | See https://tilt.jeremyevans.net for formatted documentation for Tilt. Basic Usage ----------- Instant gratification: ``` ruby require 'tilt' require 'tilt/erb' template = Tilt.new('templates/foo.erb') => # output = template.render => "Hello world!" ``` It's recommended that calling programs explicitly require the Tilt template engine libraries (like 'tilt/erb' above) at load time, or finalize the mapping (see section below). Tilt attempts to lazy require the template engine library the first time a template is created, but this is prone to error in threaded environments. The Tilt::Template class is an abstract base class that used by all supported template engines. Each template class adheres to the same interface for creation and rendering. In the instant gratification example, we let Tilt determine the template implementation class based on the filename, but Tilt::Template implementations can also be used directly: ``` ruby require 'tilt/haml' template = Tilt::HamlTemplate.new('templates/foo.haml') output = template.render ``` The `render` method takes an optional evaluation scope and locals hash arguments. Here, the template is evaluated within the context of the `Person` object with locals `x` and `y`: ``` ruby require 'tilt/erb' template = Tilt::ERBTemplate.new('templates/foo.erb') joe = Person.find('joe') output = template.render(joe, :x => 35, :y => 42) ``` If no scope is provided, the template is evaluated within the context of an object created with `Object.new`. A single `Template` instance's `render` method may be called multiple times with different scope and locals arguments. Continuing the previous example, we render the same compiled template but this time in jane's scope: ``` ruby jane = Person.find('jane') output = template.render(jane, :x => 22, :y => nil) ``` Blocks can be passed to `render` for templates that support running arbitrary ruby code (usually with some form of `yield`). For instance, assuming the following in `foo.erb`: ``` ruby Hey <%= yield %>! ``` The block passed to `render` is called on `yield`: ``` ruby template = Tilt::ERBTemplate.new('foo.erb') template.render { 'Joe' } # => "Hey Joe!" ``` For template engines that always result in the same output for the same template and do not accept local variables, scope class, or yield, the Tilt::StaticTemplate class should be used instead of Tilt::Template. Fixed Locals ------------ By default, Tilt templates that support local variables can be called with any locals, and a separate template method is compiled for each combination of local variable names. This causes multiple issues: * It is inefficient, especially for large templates that are called with many combinations of locals. * It hides issues if unused local variable names are passed to the template * It does not support default values for local variables * It does not support required local variables * It does not support cases where you want to pass values via a keyword splat * It does not support named blocks You can pass the `:fixed_locals` option when creating the template to fix the local variables. This will only compile a single template method per template (per scope class, see below). The value of the `:fixed_locals` option is a Ruby method parameter string, which should start and end with parentheses. For example, if the template does not use local variables, you can set it to `"()"`. This will cause an ArgumentError to be raised if you call the template with locals: ``` ruby template = Tilt::ERBTemplate.new('templates/foo.erb', fixed_locals: "()") output = template.render(Object.new) # No ArgumentError output = template.render(Object.new, x: 1) # ArgumentError ``` If the template must be passed the `x` local variable to work correctly, and optionally can be provided the `y` local variable: ``` ruby template = Tilt::ERBTemplate.new('templates/foo.erb', fixed_locals: "(x:, y: nil)") output = template.render(Object.new) # ArgumentError output = template.render(Object.new, x: 1) # No ArgumentError output = template.render(Object.new, x: 1, y: 2) # No ArgumentError output = template.render(Object.new, x: 1, y: 2, z: 3) # ArgumentError ``` If the template wants to accept arbitrary local variables, in order to pass the variables to a method inside the template, you can provide a keyword splat or a single positional argument (with an optional empty hash value if you want to support being called with no local variables): ``` ruby template = Tilt::ERBTemplate.new('templates/foo.erb', fixed_locals: "(**args)") # or "(args={})" ``` If you would like to name the block passed to the template, so you can pass it to a method inside the template: ``` ruby template = Tilt::ERBTemplate.new('templates/foo.erb', fixed_locals: "(&block)") ``` Embedded Fixed Locals --------------------- In many cases, Tilt is used in situations where you do not have direct control over the options passed when creating each separate template. In these cases and others, it can be helpful to embed the fixed locals inside the template using a magic comment. This can be enabled using the `:extract_fixed_locals` template option. It can also be enabled globally via: ``` ruby Tilt.extract_fixed_locals = true ``` If `:extract_fixed_locals` option is given, or extraction is globally enabled, and the `:fixed_locals` option is not provided when creating the template, Tilt will scan the template code looking for a magic comment of the form (whitespace around `locals:` is optional but recommended): ``` # locals: () ``` In ERB templates, you can use the following comment format: ``` <%# locals: () %> ``` In string templates, it is a little ackward, but still possible (note that the closing `}` goes on a separate line: ``` #{# locals: () } ``` If Tilt finds the magic comment, it will use it as fixed locals. To disable the scanning for fixed locals even if `Tilt.extract_fixed_locals = true` is set, pass the `fixed_locals: false` or `extract_fixed_locals: false` option. When embedded fixed locals are supported, it can be useful to support a default for fixed locals if they are not specified in the template. This is useful mostly to default templates to not supporting local variables without having to specify that in each template. Tilt support this via the `:default_fixed_locals` option. To recap, in order of preference, Tilt will use fixed locals from the following sources: * `:fixed_locals` template option * embedded fixed locals magic comment (if `:extract_fixed_locals` template option is given or `Tilt.extract_fixed_locals = true`) * `:default_fixed_locals` template option It is expected that embedded fixed locals magic comments will be supported by default in Tilt 3 (i.e. `Tilt.extract_fixed_locals` will default to `true`). # `:scope_class` option You can now specify the `:scope_class` option when creating the template, which will fix the scope class for the template. By default, Tilt uses the class of the provide scope, and will compile a separate method per scope class. By using the `:scope_class` option to fix the scope class, and using fixed locals, you can ensure only a single template method is compiled per Tilt::Template instance. Template Mappings ----------------- The Tilt::Mapping class includes methods for associating template implementation classes with filename patterns and for locating/instantiating template classes based on those associations. The Tilt module has a global instance of `Mapping` that is populated with the table of template engines above. The Tilt.register method associates a filename pattern with a specific template implementation. To use ERB for files ending in a `.bar` extension: ``` ruby >> Tilt.register Tilt::ERBTemplate, 'bar' >> Tilt.new('views/foo.bar') => # ``` Retrieving the template class for a file or file extension: ``` ruby >> Tilt['foo.bar'] => Tilt::ERBTemplate >> Tilt['haml'] => Tilt::HamlTemplate ``` Retrieving a list of template classes for a file: ``` ruby >> Tilt.templates_for('foo.bar') => [Tilt::ERBTemplate] >> Tilt.templates_for('foo.haml.bar') => [Tilt::ERBTemplate, Tilt::HamlTemplate] ``` The template class is determined by searching for a series of decreasingly specific name patterns. When creating a new template with `Tilt.new('views/foo.html.erb')`, we check for the following template mappings: 1. `views/foo.html.erb` 2. `foo.html.erb` 3. `html.erb` 4. `erb` Template Pipelines ------------------ In some cases, it is useful to take the output of one template engine, and use it as input to another template engine. This can be useful when a template engine does not support locals or a scope, and you want to customize the output per different locals. For example, let's say you have an scss file that you want to allow customization with erb, such as: ```scss .foo { .bar { .<%= hide_class %> { display: none; } } } ``` You can do this manually: ``` ruby scss = Tilt.new("file.scss.erb").render(nil, hide_class: 'baz') css = Tilt.new("scss"){scss}.render ``` A more automated way to handle it is to register a template pipeline: ``` ruby Tilt.register_pipeline("scss.erb") ``` Then Tilt will automatically take the output of the erb engine, and pass it to the scss engine, automating the above code. ``` ruby css = Tilt.new("file.scss.erb").render(nil, hide_class: 'baz') ``` Finalizing Mappings ------------------- By default, Tilt::Mapping instances will lazy load files for template classes, and will allow for registering an unregistering template classes. To make sure this is safe in a multithreaded environment, a mutex is used to synchronize access. To improve performance, and prevent additional lazy loading of template classes, you can finalize mappings. Finalizing a mapping returns a new finalized mapping that is frozen, cannot be modified, and will not lazy load template classes not already loaded. Users of Tilt are encouraged to manually require the template libraries they desire to use, and then freeze the mappings. Tilt.finalize! will replace Tilt's default mapping with a finalized versions, as well as freeze Tilt so that no further changes can be made. ``` ruby require 'tilt/erubi' require 'tilt/string' require 'tilt/sass' Tilt.finalize! Tilt['erb'] # => Tilt::ErubiTemplate Tilt['str'] # => Tilt::StringTemplate Tilt['scss'] # => Tilt::ScssTemplate Tilt['haml'] # => nil # even if haml is installed ``` Encodings --------- Tilt needs to know the encoding of the template in order to work properly: Tilt will use `Encoding.default_external` as the encoding when reading external files. If you're mostly working with one encoding (e.g. UTF-8) we *highly* recommend setting this option. When providing a custom reader block (`Tilt.new { custom_string }`) you'll have ensure the string is properly encoded yourself. Most of the template engines in Tilt also allows you to override the encoding using the `:default_encoding`-option: ``` ruby tmpl = Tilt.new('hello.erb', :default_encoding => 'Big5') ``` Ultimately it's up to the template engine how to handle the encoding: It might respect `:default_encoding`, it might always assume it's UTF-8 (like CoffeeScript), or it can do its own encoding detection. Template Compilation -------------------- Tilt compiles generated Ruby source code produced by template engines and reuses it on subsequent template invocations. Benchmarks show this yields a 5x-10x performance increase over evaluating the Ruby source on each invocation. Template compilation is currently supported for these template engines: StringTemplate, ERB, Erubi, Etanni, Haml, Nokogiri, Builder, CSV, Prawn, and Yajl. LICENSE ------- Tilt is distributed under the MIT license. See the `COPYING` file for more info. tilt-2.7.0/Rakefile000066400000000000000000000014301513021765100141400ustar00rootroot00000000000000task :default => [:test] desc "Run tests" task :test do sh "#{FileUtils::RUBY} #{"-w" if RUBY_VERSION >= '3'} #{'-W:strict_unused_block' if RUBY_VERSION >= '3.4'} test/all.rb" end desc "Generate rdoc" task :rdoc do rdoc_dir = "rdoc" rdoc_opts = ["--line-numbers", '--title', 'Tilt'] begin gem 'hanna' rdoc_opts.concat(['-f', 'hanna']) rescue Gem::LoadError end rdoc_opts.concat(['--main', 'README.md', "-o", rdoc_dir] + %w"README.md CHANGELOG.md COPYING" + Dir["lib/**/*.rb"] ) FileUtils.rm_rf(rdoc_dir) require "rdoc" RDoc::RDoc.new.document(rdoc_opts) end desc "Run tests with coverage" task :test_cov do ENV['COVERAGE'] = '1' sh "#{FileUtils::RUBY} test/all.rb" end desc 'Build packages' task :package do sh "gem build tilt.gemspec" end tilt-2.7.0/bin/000077500000000000000000000000001513021765100132455ustar00rootroot00000000000000tilt-2.7.0/bin/tilt000077500000000000000000000001131513021765100141420ustar00rootroot00000000000000#!/usr/bin/env ruby require_relative '../lib/tilt/cli' exit Tilt::CLI.run tilt-2.7.0/docs/000077500000000000000000000000001513021765100134255ustar00rootroot00000000000000tilt-2.7.0/docs/common.css000066400000000000000000000002101513021765100154200ustar00rootroot00000000000000body { line-height: 1.5; font-size: 14px; } .frames #content { margin: 0; } #content { margin: 0 auto; max-width: 720px; } tilt-2.7.0/lib/000077500000000000000000000000001513021765100132435ustar00rootroot00000000000000tilt-2.7.0/lib/tilt.rb000066400000000000000000000152111513021765100145440ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'tilt/mapping' require_relative 'tilt/template' # Namespace for Tilt. This module is not intended to be included anywhere. module Tilt # Current version. VERSION = '2.7.0' EMPTY_ARRAY = [].freeze private_constant :EMPTY_ARRAY EMPTY_HASH = {}.freeze private_constant :EMPTY_HASH @default_mapping = Mapping.new @extract_fixed_locals = false # Replace the default mapping with a finalized version of the default # mapping. This can be done to improve performance after the template # libraries you desire to use have already been loaded. Once this is # is called, all attempts to modify the default mapping will fail. # This also freezes Tilt itself. def self.finalize! return self if @default_mapping.is_a?(FinalizedMapping) class << self prepend(Module.new do def lazy_map(*) raise "Tilt.#{__callee__} not supported after Tilt.finalize! has been called" end alias register lazy_map alias register_lazy lazy_map alias register_pipeline lazy_map alias prefer lazy_map end) end @default_mapping = @default_mapping.finalized freeze end # @private def self.lazy_map @default_mapping.lazy_map end # @see Tilt::Mapping#register def self.register(template_class, *extensions) @default_mapping.register(template_class, *extensions) end # @see Tilt::Mapping#register_lazy def self.register_lazy(class_name, file, *extensions) @default_mapping.register_lazy(class_name, file, *extensions) end # @see Tilt::Mapping#register_pipeline def self.register_pipeline(ext, options=EMPTY_HASH) @default_mapping.register_pipeline(ext, options) end # @see Tilt::Mapping#registered? def self.registered?(ext) @default_mapping.registered?(ext) end # @see Tilt::Mapping#new def self.new(file, line=nil, options=nil, &block) @default_mapping.new(file, line, options, &block) end # @see Tilt::Mapping#[] def self.[](file) @default_mapping[file] end # @see Tilt::Mapping#template_for def self.template_for(file) @default_mapping.template_for(file) end # @see Tilt::Mapping#templates_for def self.templates_for(file) @default_mapping.templates_for(file) end class << self # @return [Tilt::Mapping] the main mapping object attr_reader :default_mapping # Whether to extract fixed locals from templates by scanning the # template content. attr_accessor :extract_fixed_locals # Alias register as prefer for Tilt 1.x compatibility. alias prefer register end # Extremely simple template cache implementation. Calling applications # create a Tilt::Cache instance and use #fetch with any set of hashable # arguments (such as those to Tilt.new): # # cache = Tilt::Cache.new # cache.fetch(path, line, options) { Tilt.new(path, line, options) } # # Subsequent invocations return the already loaded template object. # # @note # Tilt::Cache is a thin wrapper around Hash. It has the following # limitations: # * Not thread-safe. # * Size is unbounded. # * Keys are not copied defensively, and should not be modified after # being passed to #fetch. More specifically, the values returned by # key#hash and key#eql? should not change. # If this is too limiting for you, use a different cache implementation. class Cache def initialize @cache = {} end # Caches a value for key, or returns the previously cached value. # If a value has been previously cached for key then it is # returned. Otherwise, block is yielded to and its return value # which may be nil, is cached under key and returned. # @yield # @yieldreturn the value to cache for key def fetch(*key) @cache.fetch(key) do @cache[key] = yield end end # Clears the cache. def clear @cache = {} end end # :nocov: # TILT3: Remove Tilt::Cache deprecate_constant :Cache if respond_to?(:deprecate_constant, true) # :nocov: # Template Implementations ================================================ # ERB register_lazy :ERBTemplate, 'tilt/erb', 'erb', 'rhtml' register_lazy :ErubiTemplate, 'tilt/erubi', 'erb', 'rhtml', 'erubi' # Markdown register_lazy :KramdownTemplate, 'tilt/kramdown', 'markdown', 'mkd', 'md' register_lazy :RDiscountTemplate, 'tilt/rdiscount', 'markdown', 'mkd', 'md' register_lazy :RedcarpetTemplate, 'tilt/redcarpet', 'markdown', 'mkd', 'md' register_lazy :CommonMarkerTemplate, 'tilt/commonmarker', 'markdown', 'mkd', 'md' register_lazy :PandocTemplate, 'tilt/pandoc', 'markdown', 'mkd', 'md' # Rest (sorted by name) register_lazy :AsciidoctorTemplate, 'tilt/asciidoc', 'ad', 'adoc', 'asciidoc' register_lazy :BabelTemplate, 'tilt/babel', 'es6', 'babel', 'jsx' register_lazy :BuilderTemplate, 'tilt/builder', 'builder' register_lazy :CSVTemplate, 'tilt/csv', 'rcsv' register_lazy :CoffeeScriptTemplate, 'tilt/coffee', 'coffee' register_lazy :CoffeeScriptLiterateTemplate, 'tilt/coffee', 'litcoffee' register_lazy :EtanniTemplate, 'tilt/etanni', 'etn', 'etanni' register_lazy :HamlTemplate, 'tilt/haml', 'haml' register_lazy :LiquidTemplate, 'tilt/liquid', 'liquid' register_lazy :LiveScriptTemplate, 'tilt/livescript','ls', 'livescript' register_lazy :MarkabyTemplate, 'tilt/markaby', 'mab' register_lazy :NokogiriTemplate, 'tilt/nokogiri', 'nokogiri' register_lazy :PlainTemplate, 'tilt/plain', 'html' register_lazy :PrawnTemplate, 'tilt/prawn', 'prawn' register_lazy :RDocTemplate, 'tilt/rdoc', 'rdoc' register_lazy :RadiusTemplate, 'tilt/radius', 'radius' register_lazy :RedClothTemplate, 'tilt/redcloth', 'textile' register_lazy :RstPandocTemplate, 'tilt/rst-pandoc', 'rst' register_lazy :SassTemplate, 'tilt/sass', 'sass' register_lazy :ScssTemplate, 'tilt/sass', 'scss' register_lazy :SlimTemplate, 'tilt/slim', 'slim' register_lazy :StringTemplate, 'tilt/string', 'str' register_lazy :TypeScriptTemplate, 'tilt/typescript', 'ts', 'tsx' register_lazy :YajlTemplate, 'tilt/yajl', 'yajl' # TILT3: Remove # Deprecated lazy loading of external template engines register_lazy 'Tilt::HandlebarsTemplate', 'tilt/_handlebars', 'handlebars', 'hbs' register_lazy 'Tilt::OrgTemplate', 'tilt/_org', 'org' register_lazy 'Tilt::OrgTemplate', 'tilt/_emacs_org', 'org' register_lazy 'Tilt::JbuilderTemplate', 'tilt/_jbuilder', 'jbuilder' end tilt-2.7.0/lib/tilt/000077500000000000000000000000001513021765100142175ustar00rootroot00000000000000tilt-2.7.0/lib/tilt/_emacs_org.rb000066400000000000000000000002371513021765100166440ustar00rootroot00000000000000warn "Lazy loading of emacs org templates is deprecated and will be removed in Tilt 3. Require tilt/emacs_org manually.", uplevel: 1 require "tilt/emacs_org" tilt-2.7.0/lib/tilt/_handlebars.rb000066400000000000000000000002421513021765100170040ustar00rootroot00000000000000warn "Lazy loading of handlebars templates is deprecated and will be removed in Tilt 3. Require tilt/handlebars manually.", uplevel: 1 require "tilt/handlebars" tilt-2.7.0/lib/tilt/_jbuilder.rb000066400000000000000000000002341513021765100165020ustar00rootroot00000000000000warn "Lazy loading of jbuilder templates is deprecated and will be removed in Tilt 3. Require tilt/jbuilder manually.", uplevel: 1 require "tilt/jbuilder" tilt-2.7.0/lib/tilt/_org.rb000066400000000000000000000002151513021765100154700ustar00rootroot00000000000000warn "Lazy loading of org templates is deprecated and will be removed in Tilt 3. Require org-ruby manually.", uplevel: 1 require "org-ruby" tilt-2.7.0/lib/tilt/asciidoc.rb000066400000000000000000000010301513021765100163140ustar00rootroot00000000000000# frozen_string_literal: true # = AsciiDoc # # Asciidoctor implementation for AsciiDoc # # Asciidoctor is an open source, pure-Ruby processor for # converting AsciiDoc documents or strings into HTML 5, # DocBook 4.5 and other formats. # # === See also # # * http://asciidoc.org # * http://asciidoctor.github.com require_relative 'template' require 'asciidoctor' Tilt::AsciidoctorTemplate = Tilt::StaticTemplate.subclass do @options[:header_footer] = false if @options[:header_footer].nil? Asciidoctor.render(@data, @options) end tilt-2.7.0/lib/tilt/babel.rb000066400000000000000000000004231513021765100156100ustar00rootroot00000000000000# frozen_string_literal: true # = Babel # # require_relative 'template' require 'babel/transpiler' Tilt::BabelTemplate = Tilt::StaticTemplate.subclass(mime_type: 'application/javascript') do @options[:filename] ||= @file Babel::Transpiler.transform(@data)["code"] end tilt-2.7.0/lib/tilt/builder.rb000066400000000000000000000014421513021765100161730ustar00rootroot00000000000000# frozen_string_literal: true # = Builder # require_relative 'template' require 'builder' module Tilt # Builder template implementation. class BuilderTemplate < Template self.default_mime_type = 'text/xml' def prepare @options[:indent] ||= 2 end def evaluate(scope, locals, &block) if @data.respond_to?(:to_str) unless locals[:xml] locals = Hash[locals] locals[:xml] = xml_builder end return super end xml = locals[:xml] || xml_builder @data.call(xml) xml.target! end def precompiled_postamble(locals) "xml.target!" end def precompiled_template(locals) @data.to_str end private def xml_builder ::Builder::XmlMarkup.new(options) end end end tilt-2.7.0/lib/tilt/cli.rb000066400000000000000000000101361513021765100153140ustar00rootroot00000000000000# frozen_string_literal: true require_relative '../tilt' require 'optparse' module Tilt::CLI USAGE = (< Process template and write output to stdout. With no or when is '-', read template from stdin and use the --type option to determine the template's type. Options -l, --list List template engines + file patterns and exit -t, --type= Use this template engine; required if no -y, --layout= Use as a layout template -D= Define variable as -d, --define-file= Load YAML from and use for variables --vars= Evaluate to Hash and use for variables -h, --help Show this help message Convert markdown to HTML: $ tilt foo.markdown > foo.html Process ERB template: $ echo "Answer: <%= 2 + 2 %>" | tilt -t erb Answer: 4 Define variables: $ echo "Answer: <%= 2 + n %>" | tilt -t erb --vars="{:n=>40}" Answer: 42 $ echo "Answer: <%= 2 + n.to_i %>" | tilt -t erb -Dn=40 Answer: 42 USAGE private_constant :USAGE # Backbone of the tilt command line utility. Allows mocking input/output # for simple testing. Returns program exit code. def self.run(argv: ARGV, stdout: $stdout, stdin: $stdin, stderr: $stderr, script_name: File.basename($0)) pattern = nil layout = nil locals = {} abort = proc do |msg| stderr.puts msg return 1 end OptionParser.new do |o| o.program_name = script_name # list all available template engines o.on("-l", "--list") do groups = {} Tilt.lazy_map.each do |pattern,engines| engines.each do |engine,| engine = engine.split('::').last.sub(/Template\z/, '') (groups[engine] ||= []) << pattern end end groups.sort { |(k1,v1),(k2,v2)| k1 <=> k2 }.each do |engine,files| stdout.printf "%-20s %s\n", engine, files.sort.join(', ') end return 0 end # the template type / pattern o.on("-t", "--type=PATTERN", String) do |val| abort.("unknown template type: #{val}") unless Tilt[val] pattern = val end # pass template output into the specified layout template o.on("-y", "--layout=FILE", String) do |file| paths = [file, "~/.tilt/#{file}", "/etc/tilt/#{file}"] layout = paths. map { |p| File.expand_path(p) }. find { |p| File.exist?(p) } abort.("no such layout: #{file}") if layout.nil? end # define a local variable o.on("-D", "--define=PAIR", String) do |pair| key, value = pair.split(/[=:]/, 2) locals[key.to_sym] = value end # define local variables from YAML or JSON o.on("-d", "--define-file=FILE", String) do |file| require 'yaml' abort.("no such define file: #{file}") unless File.exist? file hash = File.open(file, 'r:bom|utf-8') { |f| YAML.load(f.read) } abort.("vars must be a Hash, not instance of #{hash.class}") unless hash.is_a?(Hash) hash.each { |key, value| locals[key.to_sym] = value } end # define local variables using a Ruby hash o.on("--vars=RUBY") do |ruby| hash = eval(ruby) abort.("vars must be a Hash, not instance of #{hash.class}") unless hash.is_a?(Hash) hash.each { |key, value| locals[key.to_sym] = value } end o.on_tail("-h", "--help") do stdout.puts USAGE return 0 end end.parse!(argv) file = argv.first || '-' pattern = file if pattern.nil? abort.("template type not given. see: #{script_name} --help") if ['-', ''].include?(pattern) engine = Tilt[pattern] abort.("template engine not found for: #{pattern}") unless engine template = engine.new(file) { if file == '-' stdin.read else File.read(file) end } output = template.render(self, locals) # process layout output = Tilt.new(layout).render(self, locals) { output } if layout stdout.write(output) 0 end end tilt-2.7.0/lib/tilt/coffee.rb000066400000000000000000000017571513021765100160050ustar00rootroot00000000000000# frozen_string_literal: true # CoffeeScript / Literate CoffeeScript template implementation. # # CoffeeScript templates do not support object scopes, locals, or yield. # # === See also # # * http://coffeescript.org # # === Related modules # # * Tilt::CoffeeScriptTemplate # * Tilt::CoffeeScriptLiterateTemplate require_relative 'template' require 'coffee_script' module Tilt class CoffeeScriptTemplate < StaticTemplate self.default_mime_type = 'application/javascript' @default_bare = false class << self attr_accessor :default_bare end def self.literate? false end def prepare if !@options.key?(:bare) and !@options.key?(:no_wrap) @options[:bare] = self.class.default_bare end @options[:literate] ||= self.class.literate? @output = CoffeeScript.compile(@data, @options) end end class CoffeeScriptLiterateTemplate < CoffeeScriptTemplate @default_bare = false def self.literate? true end end end tilt-2.7.0/lib/tilt/commonmarker.rb000066400000000000000000000066311513021765100172440ustar00rootroot00000000000000# frozen_string_literal: true # # = Markdown (markdown, md, mkd) # # Markdown is a lightweight markup language, created by John Gruber # and Aaron Swartz. For any markup that is not covered by Markdown’s syntax, HTML # is used. Marking up plain text with Markdown markup is easy and Markdown # formatted texts are readable. # # === Example # # Hello Markdown Templates # ======================== # # Hello World. This is a paragraph. # # === Usage # # To wrap a Markdown formatted document with a layout: # # layout = Tilt['erb'].new do # "<%= yield %>" # end # data = Tilt['md'].new { "# hello tilt" } # layout.render { data.render } # # => "

hello tilt

\n" # # === Options # # ==== :smartypants => true|false # # Set true to enable [Smarty Pants][smartypants] style punctuation replacement. # # ==== :escape_html => true|false # # Set true disallow raw HTML in Markdown contents. HTML is converted to # literal text by escaping < characters. # # === See also # # * {Markdown Syntax Documentation}[http://daringfireball.net/projects/markdown/syntax] require_relative 'template' require 'commonmarker' if defined?(::Commonmarker) aliases = { :smartypants => :smart }.freeze parse_opts = [ :smart, :default_info_string, ].freeze render_opts = [ :hardbreaks, :github_pre_lang, :width, :unsafe, :escape, :sourcepos, ].freeze exts = [ :strikethrough, :tagfilter, :table, :autolink, :tasklist, :superscript, :header_ids, :footnotes, :description_lists, :front_matter_delimiter, :shortcodes, ].freeze Tilt::CommonMarkerTemplate = Tilt::StaticTemplate.subclass do parse_options = @options.select { |key, _| parse_opts.include?(key.downcase) }.transform_keys(&:downcase) parse_options.merge!(@options.select { |key, _| aliases.has_key?(key) }.transform_keys { |key| aliases[key] }) render_options = @options.select { |key, _| render_opts.include?(key.downcase) }.transform_keys(&:downcase) extensions = @options.select { |key, _| exts.include?(key) }.transform_keys(&:downcase) Commonmarker.to_html(@data, options: { parse: parse_options, render: render_options, extension: extensions }) end # :nocov: else aliases = { :smartypants => :SMART }.freeze parse_opts = [ :FOOTNOTES, :LIBERAL_HTML_TAG, :SMART, :smartypants, :STRIKETHROUGH_DOUBLE_TILDE, :UNSAFE, :VALIDATE_UTF8, ].freeze render_opts = [ :FOOTNOTES, :FULL_INFO_STRING, :GITHUB_PRE_LANG, :HARDBREAKS, :NOBREAKS, :SAFE, # Removed in v0.18.0 (2018-10-17) :SOURCEPOS, :TABLE_PREFER_STYLE_ATTRIBUTES, :UNSAFE, ].freeze exts = [ :autolink, :strikethrough, :table, :tagfilter, :tasklist, ].freeze Tilt::CommonMarkerTemplate = Tilt::StaticTemplate.subclass do extensions = exts.select do |extension| @options[extension] end parse_options, render_options = [parse_opts, render_opts].map do |opts| opts = opts.select do |option| @options[option] end.map! do |option| aliases[option] || option end opts = :DEFAULT unless opts.any? opts end CommonMarker.render_doc(@data, parse_options, extensions).to_html(render_options, extensions) end end # :nocov: tilt-2.7.0/lib/tilt/csv.rb000066400000000000000000000021511513021765100153360ustar00rootroot00000000000000# frozen_string_literal: true # = CSV # # CSV Template implementation. # # === Example # # # Example of csv template # tpl = <<-EOS # # header # csv << ['NAME', 'ID'] # # # data rows # @people.each do |person| # csv << [person[:name], person[:id]] # end # EOS # # @people = [ # {:name => "Joshua Peek", :id => 1}, # {:name => "Ryan Tomayko", :id => 2}, # {:name => "Simone Carletti", :id => 3} # ] # # template = Tilt::CSVTemplate.new { tpl } # template.render(self) # # === See also # # * http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html # # === Related module # # * Tilt::CSVTemplate require_relative 'template' require 'csv' module Tilt class CSVTemplate < Template self.default_mime_type = 'text/csv' def prepare @outvar = @options.delete(:outvar) || '_csvout' end def precompiled_template(locals) <<-RUBY #{@outvar} = CSV.generate(**#{@options}) do |csv| #{@data} end RUBY end def precompiled(locals) source, offset = super [source, offset + 1] end end end tilt-2.7.0/lib/tilt/erb.rb000066400000000000000000000070401513021765100153150ustar00rootroot00000000000000# frozen_string_literal: true # = ERB (erb, rhtml) # # ERB is a simple but powerful template languge for Ruby. In Tilt it's # backed by {Erubi}[rdoc-ref:lib/tilt/erubi.rb] (if installed on your system] or by # {erb.rb}[rdoc-ref:lib/tilt/erb.rb] (which is included in Ruby's standard library]. This # documentation applies to both implementations. # # === Example # # Hello <%= world %>! # # === Usage # # ERB templates support custom evaluation scopes and locals: # # >> require 'erb' # >> template = Tilt.new('hello.html.erb') # >> template.render(self, :world => 'World!') # => "Hello World!" # # Or, use Tilt['erb'] directly to process strings: # # template = Tilt['erb'].new { "Hello <%= world %>!" } # template.render(self, :world => 'World!') # # The Tilt::ERBTemplate class is registered for all files ending in .erb or # .rhtml by default, but with a *lower* priority than ErubiTemplate. # If you specifically want to use ERB, it's recommended to use # #prefer: # # Tilt.prefer Tilt::ERBTemplate # # __NOTE:__ It's suggested that your program require 'erb' at load time when # using this template engine within a threaded environment. # # === Options # # ==== :trim => trim # # The ERB trim mode flags. This is a string consisting of any combination of the # following characters: # # * '>' omits newlines for lines ending in > # * '<>' omits newlines for lines starting with <% and ending in %> # * '%' enables processing of lines beginning with % # * true is an alias of <> # # ==== :outvar => '_erbout' # # The name of the variable used to accumulate template output. This can be # any valid Ruby expression but must be assignable. By default a local # variable named _erbout is used. # # ==== :freeze => false # # If set to true, will set the frozen_string_literal flag in the compiled # template code, so that string literals inside the templates will be frozen. # # === See also # # * http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html # # === Related module # # * Tilt::ERBTemplate require_relative 'template' require 'erb' module Tilt class ERBTemplate < Template SUPPORTS_KVARGS = ::ERB.instance_method(:initialize).parameters.assoc(:key) rescue false def prepare @freeze_string_literals = !!@options[:freeze] @outvar = @options[:outvar] || '_erbout' trim = case @options[:trim] when false nil when nil, true '<>' else @options[:trim] end @engine = if SUPPORTS_KVARGS ::ERB.new(@data, trim_mode: trim, eoutvar: @outvar) # :nocov: else ::ERB.new(@data, options[:safe], trim, @outvar) # :nocov: end end def precompiled_template(locals) source = @engine.src source end def precompiled_preamble(locals) <<-RUBY begin __original_outvar = #{@outvar} if defined?(#{@outvar}) #{super} RUBY end def precompiled_postamble(locals) <<-RUBY #{super} ensure #{@outvar} = __original_outvar end RUBY end # ERB generates a line to specify the character coding of the generated # source in 1.9. Account for this in the line offset. def precompiled(locals) source, offset = super [source, offset + 1] end def freeze_string_literals? @freeze_string_literals end end end tilt-2.7.0/lib/tilt/erubi.rb000066400000000000000000000054271513021765100156620ustar00rootroot00000000000000# frozen_string_literal: true # = Erubi (erb, rhtml, erubi) # # {Erubi}[https://github.com/jeremyevans/erubi] is an ERB implementation that uses the same algorithm as # the erubis gem, but is maintained and offers numerous improvements. # # All the documentation of {ERB}[rdoc-ref:lib/tilt/erb.rb] applies in addition to the following: # # === Usage # # The Tilt::ErubiTemplate class is registered for all files ending in .erb or # .rhtml by default, with the *highest* priority. # # __NOTE:__ It's suggested that your program require 'erubi' at load time when # using this template engine within a threaded environment. # # === Options # # ==== :engine_class => Erubi::Engine # # Allows you to specify a custom engine class to use instead of the # default which is Erubi::Engine. # # ==== Other # # Other options are passed to the constructor of the engine class. # # ErubiTemplate supports the following additional options, in addition # to the options supported by the Erubi engine: # # :engine_class :: allows you to specify a custom engine class to use # instead of the default (which is ::Erubi::Engine). # # === See also # # * {Erubi Home}[https://github.com/jeremyevans/erubi] # # === Related module # # * Tilt::ErubiTemplate require_relative 'template' require 'erubi' module Tilt class ErubiTemplate < Template def prepare @options[:preamble] = false @options[:postamble] = false @options[:ensure] = true engine_class = @options[:engine_class] || Erubi::Engine # If :freeze option is given, the intent is to setup frozen string # literals in the template. So enable frozen string literals in the # code Tilt generates if the :freeze option is given. if @freeze_string_literals = !!@options[:freeze] # Passing the :freeze option to Erubi sets the # frozen-string-literal magic comment, which doesn't have an effect # with Tilt as Tilt wraps the resulting code. Worse, the magic # comment appearing not at the top of the file can cause a warning. # So remove the :freeze option before passing to Erubi. @options.delete(:freeze) # Erubi by default appends .freeze to template literals on Ruby 2.1+, # but that is not necessary and slows down code when Tilt is using # frozen string literals, so pass the :freeze_template_literals # option to not append .freeze. @options[:freeze_template_literals] = false end @engine = engine_class.new(@data, @options) @outvar = @engine.bufvar @src = @engine.src @engine end def precompiled_template(locals) @src end def freeze_string_literals? @freeze_string_literals end end end tilt-2.7.0/lib/tilt/etanni.rb000066400000000000000000000012561513021765100160260ustar00rootroot00000000000000# frozen_string_literal: true # = Etanni # # === Related module # # * Tilt::EtanniTemplate require_relative 'template' module Tilt class EtanniTemplate < Template def prepare separator = data.hash.abs chomp = "<<#{separator}.chomp" start = "\n_out_ << #{chomp}\n" stop = "\n#{separator}\n" replacement = "#{stop}\\1#{start}" temp = @data.strip temp.gsub!(/<\?r\s+(.*?)\s+\?>/m, replacement) @code = "_out_ = [<<#{separator}.chomp]\n#{temp}#{stop}_out_.join" end def precompiled_template(locals) @code end def precompiled(locals) source, offset = super [source, offset + 1] end end end tilt-2.7.0/lib/tilt/haml.rb000066400000000000000000000120111513021765100154600ustar00rootroot00000000000000# frozen_string_literal: true # = Haml (haml) # # {Haml}[https://haml.info] is a markup language that’s used to cleanly and simply describe # the HTML of any web document without the use of inline code. Haml functions as # a replacement for inline page templating systems such as PHP, ASP, and ERB, the # templating language used in most Ruby on Rails applications. However, Haml # avoids the need for explicitly coding HTML into the template, because it itself # is a description of the HTML, with some code to generate dynamic content. # ({more}[http://haml.info/about.html)] # # === Example # # %html # %head # %title= @title # %body # %h1 # Hello # = world + '!' # # === Usage # # The Tilt::HamlTemplate class is registered for all files ending in .haml # by default. Haml templates support custom evaluation scopes and locals: # # >> require 'haml' # >> template = Tilt.new('hello.haml') # => # # >> @title = "Hello Haml!" # >> template.render(self, :world => 'Haml!') # => " # # # Hello Haml! # # #

Hello Haml!

# # " # # Or, use the Tilt::HamlTemplate class directly to process strings: # # >> require 'haml' # >> template = Tilt::HamlTemplate.new { "%h1= 'Hello Haml!'" } # => # # >> template.render # => "

Hello Haml!

" # # __NOTE:__ It's suggested that your program require 'haml' at load time when # using this template engine within a threaded environment. # # === Options # # Please see the {Haml Reference}[http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options] for all available options. # # === See also # # * {#haml.docs}[http://haml.info/docs.html] # * {Haml Tutorial}[http://haml.info/tutorial.html] # * {Haml Reference}[http://haml.info/docs/yardoc/file.HAML_REFERENCE.html] # # === Related module # # * Tilt::HamlTemplate require_relative 'template' require 'haml' module Tilt # Haml template implementation. See: # http://haml.hamptoncatlin.com/ if defined?(Haml::Template) && Haml::Template < Tilt::Template # Haml >= 6 ships its own template, prefer it when available. HamlTemplate = Haml::Template else class HamlTemplate < Template self.default_mime_type = 'text/html' # Gem::Version.correct? may return false because of Haml::VERSION #=> "3.1.8 (Separated Sally)". After Haml 4, it's always correct. if Gem::Version.correct?(Haml::VERSION) && Gem::Version.new(Haml::VERSION) >= Gem::Version.new('5.0.0.beta.2') def prepare @options[:filename] = eval_file @options[:line] = @line if @options.include?(:outvar) @options[:buffer] = @options.delete(:outvar) @options[:save_buffer] = true end @engine = ::Haml::TempleEngine.new(@options) @engine.compile(@data) end def evaluate(scope, locals, &block) raise ArgumentError, 'invalid scope: must not be frozen' if scope.frozen? super end def precompiled_template(locals) @engine.precompiled_with_ambles( [], after_preamble: <<-RUBY __in_erb_template = true _haml_locals = locals RUBY ) end else # Following definitions are for Haml <= 4 and deprecated. def prepare @options[:filename] = eval_file @options[:line] = @line @engine = ::Haml::Engine.new(@data, @options) end def evaluate(scope, locals, &block) raise ArgumentError, 'invalid scope: must not be frozen' if scope.frozen? if @engine.respond_to?(:precompiled_method_return_value, true) super else @engine.render(scope, locals, &block) end end # Precompiled Haml source. Taken from the precompiled_with_ambles # method in Haml::Precompiler: # http://github.com/nex3/haml/blob/master/lib/haml/precompiler.rb#L111-126 def precompiled_template(locals) @engine.precompiled end def precompiled_preamble(locals) local_assigns = super @engine.instance_eval do <<-RUBY begin extend Haml::Helpers _hamlout = @haml_buffer = Haml::Buffer.new(haml_buffer, #{options_for_buffer.inspect}) _erbout = _hamlout.buffer __in_erb_template = true _haml_locals = locals #{local_assigns} RUBY end end def precompiled_postamble(locals) @engine.instance_eval do <<-RUBY #{precompiled_method_return_value} ensure @haml_buffer = @haml_buffer.upper if haml_buffer end RUBY end end end end end end tilt-2.7.0/lib/tilt/kramdown.rb000066400000000000000000000034531513021765100163730ustar00rootroot00000000000000# frozen_string_literal: true # = Markdown (markdown, md, mkd) # # Markdown is a lightweight markup language, created by John Gruber # and Aaron Swartz. For any markup that is not covered by Markdown’s syntax, HTML # is used. Marking up plain text with Markdown markup is easy and Markdown # formatted texts are readable. # # === Example # # Hello Markdown Templates # ======================== # # Hello World. This is a paragraph. # # === Usage # # To wrap a Markdown formatted document with a layout: # # layout = Tilt['erb'].new do # "<%= yield %>" # end # data = Tilt['md'].new { "# hello tilt" } # layout.render { data.render } # # => "

hello tilt

\n" # # === Options # # Every implementation of Markdown *should* support these options, but there are # some known problems with the Kramdown engine. # # ==== :smartypants => true|false # # Set true to enable [Smarty Pants][smartypants] style punctuation replacement. # # In Kramdown this option only applies to smart quotes. It will apply a # subset of Smarty Pants (e.g. ... to ) regardless of any option. # # ==== :escape_html => true|false # # Kramdown doesn't support this option. # # === See also # # * {Markdown Syntax Documentation}[http://daringfireball.net/projects/markdown/syntax] # * {Kramdown Markdown implementation}[https://kramdown.gettalong.org] require_relative 'template' require 'kramdown' dumb_quotes = [39, 39, 34, 34].freeze Tilt::KramdownTemplate = Tilt::StaticTemplate.subclass do # dup as Krawmdown modifies the passed option with map! @options[:smart_quotes] = dumb_quotes.dup unless @options[:smartypants] Kramdown::Document.new(@data, @options).to_html end tilt-2.7.0/lib/tilt/liquid.rb000066400000000000000000000050511513021765100160340ustar00rootroot00000000000000# frozen_string_literal: true # = Liquid (liquid) # # Liquid is designed to be a *safe* template system and therefore # does not provide direct access to execuatable scopes. In order to # support a +scope+, the +scope+ must be able to represent itself # as a hash by responding to #to_h. If the +scope+ does not respond # to #to_h it will be ignored. # # LiquidTemplate does not support yield blocks. # # === Example # # # # {{ title }} # # #

Hello {{ world }}!

# # # # === Usage # # Tilt::LiquidTemplate is registered for all files ending in .liquid by # default. Liquid templates support locals and objects that respond to # #to_h as scopes: # # >> require 'liquid' # >> require 'tilt' # >> template = Tilt.new('hello.liquid') # => # # >> scope = { :title => "Hello Liquid Templates" } # >> template.render(nil, :world => "Liquid") # => " # # # Hello Liquid Templates # # #

Hello Liquid!

# # " # # Or, use Tilt::LiquidTemplate directly to process strings: # # >> require 'liquid' # >> template = Tilt::LiquidTemplate.new { "

Hello Liquid!

" } # => # # >> template.render # => "

Hello Liquid!

" # # __NOTE:__ It's suggested that your program require 'liquid' at load # time when using this template engine within a threaded environment. # # === See also # # * {Liquid}[http://liquidmarkup.org] # * {Liquid for Programmers}[https://wiki.github.com/Shopify/liquid/liquid-for-programmers] # * {Liquid Docs}[http://liquid.rubyforge.org/] # * GitHub: {Shopify/liquid}[https://github.com/Shopify/liquid/] # # === Related module # # * Tilt::LiquidTemplate require_relative 'template' require 'liquid' module Tilt class LiquidTemplate < Template def prepare @options[:line_numbers] = true unless @options.has_key?(:line_numbers) @engine = ::Liquid::Template.parse(@data, @options) end def evaluate(scope, locs) locals = {} if scope.respond_to?(:to_h) scope.to_h.each{|k, v| locals[k.to_s] = v} end locs.each{|k, v| locals[k.to_s] = v} locals['yield'] = block_given? ? yield : '' locals['content'] = locals['yield'] @engine.render(locals) end def allows_script? false end end end tilt-2.7.0/lib/tilt/livescript.rb000066400000000000000000000006121513021765100167270ustar00rootroot00000000000000# frozen_string_literal: true # = LiveScript # # LiveScript template implementation. # # LiveScript templates do not support object scopes, locals, or yield. # # === See also # # * http://livescript.net require_relative 'template' require 'livescript' Tilt::LiveScriptTemplate = Tilt::StaticTemplate.subclass(mime_type: 'application/javascript') do LiveScript.compile(@data, @options) end tilt-2.7.0/lib/tilt/mapping.rb000066400000000000000000000325751513021765100162130ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'pipeline' module Tilt # Private internal base class for both Mapping and FinalizedMapping, for the shared methods. class BaseMapping # Instantiates a new template class based on the file. # # @raise [RuntimeError] if there is no template class registered for the # file name. # # @example # mapping.new('index.mt') # => instance of MyEngine::Template # # @see Tilt::Template.new def new(file, line=nil, options={}, &block) if template_class = self[file] template_class.new(file, line, options, &block) else fail "No template engine registered for #{File.basename(file)}" end end # Looks up a template class based on file name and/or extension. # # @example # mapping['views/hello.erb'] # => Tilt::ERBTemplate # mapping['hello.erb'] # => Tilt::ERBTemplate # mapping['erb'] # => Tilt::ERBTemplate # # @return [template class] def [](file) _, ext = split(file) ext && lookup(ext) end alias template_for [] # Looks up a list of template classes based on file name. If the file name # has multiple extensions, it will return all template classes matching the # extensions from the end. # # @example # mapping.templates_for('views/index.haml.erb') # # => [Tilt::ERBTemplate, Tilt::HamlTemplate] # # @return [Array