pax_global_header00006660000000000000000000000064146373222000014511gustar00rootroot0000000000000052 comment=a237d86a49170aed4aee6d3516e102d8d5cdd3ad tilt-2.4.0/000077500000000000000000000000001463732220000124705ustar00rootroot00000000000000tilt-2.4.0/.autotest000066400000000000000000000005301463732220000143370ustar00rootroot00000000000000require '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.4.0/.ci.gemfile000066400000000000000000000032721463732220000144770ustar00rootroot00000000000000source 'https://rubygems.org' gem 'rake' gem 'minitest' gem 'babel-transpiler' gem 'creole' gem 'erubi' gem 'erubis' gem 'liquid' gem 'livescript' gem 'nokogiri' gem 'pdf-reader' gem 'prawn', '>= 2.0.0' gem 'radius' gem 'slim' gem 'typescript-node' if RUBY_VERSION > '3.3' gem 'csv' 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 unless RUBY_VERSION < '2.4' && RUBY_ENGINE == 'jruby' gem 'pandoc-ruby' end unless RUBY_VERSION < '2.6' && RUBY_ENGINE == 'jruby' gem 'maruku' 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 'wikicloth' gem 'rinku' # dependency for wikicloth for handling links gem 'RedCloth' gem 'commonmarker' gem 'rdiscount', '>= 2.1.6' gem 'redcarpet' gem 'yajl-ruby' 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' # i18n is pulled in by wikicloth. This avoids errors # on Ruby 2.0. gem 'i18n', '<1.3' end end tilt-2.4.0/.github/000077500000000000000000000000001463732220000140305ustar00rootroot00000000000000tilt-2.4.0/.github/workflows/000077500000000000000000000000001463732220000160655ustar00rootroot00000000000000tilt-2.4.0/.github/workflows/ci.yml000066400000000000000000000013531463732220000172050ustar00rootroot00000000000000name: CI on: push: branches: [ master ] pull_request: branches: [ master ] permissions: contents: read jobs: test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: ruby: [ "2.0.0", 2.1, 2.3, 2.4, 2.5, 2.6, 2.7, "3.0", 3.1, 3.2, 3.3, jruby-9.1, jruby-9.2, jruby-9.3, jruby-9.4 ] name: ${{ matrix.ruby }} env: BUNDLE_GEMFILE: .ci.gemfile COFFEE_SCRIPT: use steps: - uses: actions/checkout@v4 # WikiCloth needs IDN # Pandoc needs Pandoc - run: sudo apt-get install -y libidn11-dev pandoc - uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} bundler-cache: true cache-version: 1 - run: bundle exec rake tilt-2.4.0/.gitignore000066400000000000000000000001151463732220000144550ustar00rootroot00000000000000/dist *.swp /vendor /.bundle /.yardoc /doc .sass-cache /tilt-*.gem /coverage tilt-2.4.0/CHANGELOG.md000066400000000000000000000220401463732220000142770ustar00rootroot00000000000000## 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.4.0/COPYING000066400000000000000000000021201463732220000135160ustar00rootroot00000000000000Copyright (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.4.0/README.md000066400000000000000000000251711463732220000137550ustar00rootroot00000000000000Tilt ==== 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 | .ad, .adoc, .asciidoc | asciidoctor | | Babel | .es6, .babel, .jsx | babel-transpiler | | Builder | .builder | builder | | CoffeeScript | .coffee | coffee-script (+ javascript) | | CoffeeScriptLiterate | .litcoffee | coffee-script (+ javascript) | | CommonMarker | .markdown, .mkd, .md | commonmarker | | Creole | .wiki, .creole | creole | | CSV | .rcsv | csv (ruby stdlib) | | ERB | .erb, .rhtml | erb (ruby stdlib) | | Erubi | .erb, .rhtml, .erubi | erubi | | Erubis | .erb, .rhtml, .erubis | erubis | | Etanni | .ern, .etanni | none | | Haml | .haml | haml | | Kramdown | .markdown, .mkd, .md | kramdown | | Liquid | .liquid | liquid | | LiveScript | .ls | livescript (+ javascript) | | Markaby | .mab | markaby | | Maruku | .markdown, .mkd, .md | maruku | | Nokogiri | .nokogiri | nokogiri | | Pandoc | .markdown, .mkd, .md | pandoc | | Plain | .html | none | | Prawn | .prawn | prawn | | Radius | .radius | radius | | RDiscount | .markdown, .mkd, .md | rdiscount | | RDoc | .rdoc | rdoc | | Redcarpet | .markdown, .mkd, .md | redcarpet | | RedCloth | .textile | redcloth | | RstPandoc | .rst | pandoc | | Slim | .slim | slim | | Sass | .sass | sass-embedded, sassc, or sass | | Scss | .scss | sass-embedded, sassc, or sass | | String | .str | none | | TypeScript | .ts | typescript (+ javascript) | | WikiCloth | .wiki, .mediawiki, .mw | wikicloth | | Yajl | .yajl | yajl-ruby | See [TEMPLATES.md][t] for detailed information on template engine options and supported features. [t]: http://github.com/jeremyevans/tilt/blob/master/docs/TEMPLATES.md "Tilt Template Engine Documentation" 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. 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 module contains generic implementation classes for 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!" ~~~ 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, Erubis, 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.4.0/Rakefile000066400000000000000000000012501463732220000141330ustar00rootroot00000000000000task :default => [:test] desc "Run tests" task :test do sh "#{FileUtils::RUBY} #{"-w" if RUBY_VERSION >= '3'} test/all.rb" end desc "Run tests with coverage" task :test_cov do ENV['COVERAGE'] = '1' sh "#{FileUtils::RUBY} test/all.rb" end begin require 'yard' YARD::Rake::YardocTask.new do |t| t.files = [ 'lib/tilt.rb', 'lib/tilt/mapping.rb', 'lib/tilt/template.rb', '-', '*.md', 'docs/*.md', ] t.options << '--no-private' << '--protected' << '-m' << 'markdown' << '--asset' << 'docs/common.css:css/common.css' end rescue LoadError end desc 'Build packages' task :package do sh "gem build tilt.gemspec" end tilt-2.4.0/bin/000077500000000000000000000000001463732220000132405ustar00rootroot00000000000000tilt-2.4.0/bin/tilt000077500000000000000000000001131463732220000141350ustar00rootroot00000000000000#!/usr/bin/env ruby require_relative '../lib/tilt/cli' exit Tilt::CLI.run tilt-2.4.0/docs/000077500000000000000000000000001463732220000134205ustar00rootroot00000000000000tilt-2.4.0/docs/TEMPLATES.md000066400000000000000000000404661463732220000153120ustar00rootroot00000000000000Tilt Templates ============== While all Tilt templates use the same basic interface for template loading and evaluation, each varies in its capabilities and available options. Detailed documentation on each supported template engine is provided below. There are also some file extensions that have several implementations (currently ERB and Markdown). These template classes have certain features which are guaranteed to work across all the implementations. If you wish to be compatible with all of these template classes, you should only depend on the cross-implementation features. * [ERB](#erb) - Generic ERB implementation (backed by erb.rb, Erubis, or Erubi) * [erb.rb](#erbrb) - `Tilt::ERBTemplate` * [Erubis](#erubis) - `Tilt::ErubisTemplate` * [Erubi](#erubi) - `Tilt::ErubiTemplate` * [Haml](#haml) - `Tilt::HamlTemplate` * [Liquid](#liquid) - `Tilt::LiquidTemplate` * Nokogiri - `Tilt::NokogiriTemplate` * Builder - `Tilt::BuilderTemplate` * Markaby - `Tilt::MarkabyTemplate` * [Radius](#radius) - `Tilt::RadiusTemplate` Tilt also includes support for CSS processors like [Sass][sass], [CoffeeScript][coffee-script] and some simple text formats. * Sass - `Tilt::SassTemplate` * Scss - `Tilt::ScssTemplate` * CoffeeScript - `Tilt::CoffeeScriptTemplate` * Literate CoffeeScript - `Tilt::CoffeeScriptLiterateTemplate` * LiveScript - `Tilt::LiveScriptTemplate` * [Textile](#redcloth) - `Tilt::RedClothTemplate` * reStructuredText - `Tilt::RstPandocTemplate` * Creole - `Tilt::CreoleTemplate` * [RDoc](#rdoc) - `Tilt::RDocTemplate` Tilt has extensive support for Markdown, backed by one of seven different implementations (depending on which are available on your system): * [Markdown](#markdown) - Generic Markdown implementation * [RDiscount](#rdiscount) - `Tilt::RDiscountTemplate` * Redcarpet - `Tilt::RedcarpetTemplate` * Kramdown - `Tilt::KramdownTemplate` * Pandoc - `Tilt::PandocTemplate` * CommonMarker - `Tilt::CommonMarkerTemplate` * Maruku - `Tilt::MarukuTemplate` ERB (`erb`, `rhtml`) -------------------- ERB is a simple but powerful template languge for Ruby. In Tilt it's backed by [Erubi](#erubi) (if installed on your system) or by [Erubis](#erubis) (if installed on your system) or by [erb.rb](#erbrb) (which is included in Ruby's standard library). This documentation applies to all three 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!') ### Options #### `:trim => trim` Omits newlines and spaces around certain lines (usually those that starts with `<%` and ends with `%>`). There isn't a specification for how trimming in ERB should work, so if you need more control over the whitespace, you should use [erb.rb](#erbrb), [Erubis](#erubis), or [Erubi](#erubi) directly. #### `: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. erb.rb (`erb`, `rhtml`) ----------------------- [ERB](#erb) implementation available in Ruby's standard library. All the documentation of [ERB](#erb) applies in addition to the following: ### Usage The `Tilt::ERBTemplate` class is registered for all files ending in `.erb` or `.rhtml` by default, but with a *lower* priority than ErubiTemplate and ErubisTemplate. 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 => true` 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 `<>` ### See also * [ERB documentation](https://docs.ruby-lang.org/en/master/ERB.html) Erubis (`erb`, `rhtml`, `erubis`) --------------------------------- [Erubis][erubis] is a fast, secure, and very extensible implementation of [ERB](#erb). All the documentation of [ERB](#erb) applies in addition to the following: ### Usage The `Tilt::ErubisTemplate` 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 Erubis, it's recommended to use `#prefer`: Tilt.prefer Tilt::ErubisTemplate __NOTE:__ It's suggested that your program `require 'erubis'` at load time when using this template engine within a threaded environment. ### Options #### `:engine_class => Erubis::Eruby` Allows you to specify a custom engine class to use instead of the default which is `Erubis::Eruby`. #### `:escape_html => false` When `true`, `Erubis::EscapedEruby` will be used as the engine class instead of the default. All content within `<%= %>` blocks will be automatically html escaped. #### Other Other options are passed to the constructor of the engine class. ### See also * [Erubis Home][erubis] Erubi (`erb`, `rhtml`, `erubi`) --------------------------------- [Erubi][erubi] is a ERB implementation that uses the same algorithm as [Erubis][erubis], but is maintained and offers numerous improvements.. All the documentation of [ERB](#erb) 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. Tilt.prefer Tilt::ErubisTemplate __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. ### See also * [Erubi Home][erubi] Haml (`haml`) ------------- [Haml][haml] 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) Liquid (`liquid`) ----------------- [Liquid][liquid] is for rendering safe templates which cannot affect the security of the server they are rendered on. ### 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 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/) Radius (`radius`) ----------------- [Radius][radius] is the template language used by [Radiant CMS][radiant]. It is a tag language designed to be valid XML/HTML. ### Example

  • !
### Usage To render a template such as the one above. scope = OpenStruct.new scope.title = "Radius Example" scope.hello = "Hello, World!" require 'radius' template = Tilt::RadiusTemplate.new('example.radius', :tag_prefix=>'r') template.render(scope, :type=>'hlist'){ "Jackpot!" } The result will be:

Radius Example

  • Hello, World!
  • Hello, World!
  • Hello, World!
Jackpot! ### See also * [Radius][radius] * [Radiant CMS][radiant] Textile (`textile`) ------------------- Textile is a lightweight markup language originally developed by Dean Allen and billed as a "humane Web text generator". Textile converts its marked-up text input to valid, well-formed XHTML and also inserts character entity references for apostrophes, opening and closing single and double quotation marks, ellipses and em dashes. Textile formatted texts are converted to HTML with the [RedCloth][redcloth] engine, which is a Ruby extension written in C. ### Example h1. Hello Textile Templates Hello World. This is a paragraph. ### Usage __NOTE:__ It's suggested that your program `require 'redcloth'` at load time when using this template engine in a threaded environment. ### See Also * [RedCloth][redcloth] reStructuredText (`rst`) ------------------- reStructuredText is a lightweight markup language originally developed by David Goodger, based on StructuredText and Setext. reStructuredText is primarily used for technical documentation in the Python programming language community, e.g. by the [Sphinx](http://www.sphinx-doc.org/en/stable/rest.html) Python documentation generator. reStructuredText formatted texts are converted to HTML with [Pandoc][pandoc], which is an application written in Haskell, with a Ruby wrapper provided by the [pandoc-ruby][pandoc-ruby] gem. ### Example Hello Rst Templates =================== Hello World. This is a paragraph. ### See Also * [Pandoc][pandoc] * [pandoc-ruby][pandoc-ruby] RDoc (`rdoc`) ------------- [RDoc][rdoc] is the simple text markup system that comes with Ruby's standard library. ### Example = Hello RDoc Templates Hello World. This is a paragraph. ### Usage __NOTE:__ It's suggested that your program `require 'rdoc'`, `require 'rdoc/markup'`, and `require 'rdoc/markup/to_html'` at load time when using this template engine in a threaded environment. ### See also * [RDoc][rdoc] Markdown (`markdown`, `md`, `mkd`) ---------------------------------- [Markdown][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. Markdown formatted texts are converted to HTML with one of these libraries: * [RDiscount](#rdiscount) - `Tilt::RDiscountTemplate` * Redcarpet - `Tilt::RedcarpetTemplate` * Kramdown - `Tilt::KramdownTemplate` * Pandoc - `Tilt::PandocTemplate` * Maruku - `Tilt::MarukuTemplate` * CommonMarker - `Tilt::CommonMarkerTemplate` ### 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 and Maruku engines. #### `: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. Maruku ignores this option and always applies smart quotes (and nothing else). #### `:escape_html => true|false` Set `true` disallow raw HTML in Markdown contents. HTML is converted to literal text by escaping `<` characters. Kramdown and Maruku don't support this option. ### See also * [Markdown Syntax Documentation](http://daringfireball.net/projects/markdown/syntax) RDiscount (`markdown`, `md`, `mkd`) ----------------------------------- [Discount][discount] is an implementation of the Markdown markup language in C. [RDiscount][rdiscount] is a Ruby wrapper around Discount. All the documentation of [Markdown](#markdown) applies in addition to the following: ### Usage The `Tilt::RDiscountTemplate` class is registered for all files ending in `.markdown`, `.md` or `.mkd` by default with the highest priority. If you specifically want to use RDiscount, it's recommended to use `#prefer`: Tilt.prefer Tilt::RDiscountTemplate __NOTE:__ It's suggested that your program `require 'rdiscount'` at load time when using this template engine within a threaded environment. ### See also * [Discount][discount] * [RDiscount][rdiscount] * GitHub: [rtomayko/rdiscount][rdiscount] [sass]: http://sass-lang.com/ "Sass" [coffee-script]: http://jashkenas.github.com/coffee-script/ "Coffee Script" [erubis]: https://github.com/kwatch/erubis "Erubis" [erubi]: https://github.com/jeremyevans/erubi "Erubi" [haml]: http://haml.info/ "Haml" [liquid]: http://www.liquidmarkup.org/ "Liquid" [radius]: http://radius.rubyforge.org/ "Radius" [radiant]: http://radiantcms.org/ "Radiant CMS" [redcloth]: http://redcloth.org/ "RedCloth" [rdoc]: http://rdoc.rubyforge.org/ "RDoc" [discount]: http://www.pell.portland.or.us/~orc/Code/discount/ "Discount" [rdiscount]: http://github.com/rtomayko/rdiscount/ "RDiscount" [smartypants]: http://daringfireball.net/projects/smartypants/ "Smarty Pants" [markdown]: http://en.wikipedia.org/wiki/Markdown "Markdown" [pandoc]: http://pandoc.org/ "Pandoc" [pandoc-ruby]: https://github.com/alphabetum/pandoc-ruby "pandoc-ruby" tilt-2.4.0/docs/common.css000066400000000000000000000002101463732220000154130ustar00rootroot00000000000000body { line-height: 1.5; font-size: 14px; } .frames #content { margin: 0; } #content { margin: 0 auto; max-width: 720px; } tilt-2.4.0/lib/000077500000000000000000000000001463732220000132365ustar00rootroot00000000000000tilt-2.4.0/lib/tilt.rb000066400000000000000000000153421463732220000145440ustar00rootroot00000000000000# 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.4.0' EMPTY_HASH = {}.freeze private_constant :EMPTY_HASH @default_mapping = Mapping.new # 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 # 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 :ErubisTemplate, 'tilt/erubis', 'erb', 'rhtml', 'erubis' register_lazy :ErubiTemplate, 'tilt/erubi', 'erb', 'rhtml', 'erubi' # Markdown register_lazy :MarukuTemplate, 'tilt/maruku', 'markdown', 'mkd', 'md' 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 :CreoleTemplate, 'tilt/creole', 'wiki', 'creole' 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 :WikiClothTemplate, 'tilt/wikicloth', 'wiki', 'mediawiki', 'mw' 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.4.0/lib/tilt/000077500000000000000000000000001463732220000142125ustar00rootroot00000000000000tilt-2.4.0/lib/tilt/_emacs_org.rb000066400000000000000000000002371463732220000166370ustar00rootroot00000000000000warn "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.4.0/lib/tilt/_handlebars.rb000066400000000000000000000002421463732220000167770ustar00rootroot00000000000000warn "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.4.0/lib/tilt/_jbuilder.rb000066400000000000000000000002341463732220000164750ustar00rootroot00000000000000warn "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.4.0/lib/tilt/_org.rb000066400000000000000000000002151463732220000154630ustar00rootroot00000000000000warn "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.4.0/lib/tilt/asciidoc.rb000066400000000000000000000010051463732220000163110ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'asciidoctor' # AsciiDoc see: http://asciidoc.org/ # Asciidoctor implementation for AsciiDoc see: # http://asciidoctor.github.com/ # # Asciidoctor is an open source, pure-Ruby processor for # converting AsciiDoc documents or strings into HTML 5, # DocBook 4.5 and other formats. Tilt::AsciidoctorTemplate = Tilt::StaticTemplate.subclass do @options[:header_footer] = false if @options[:header_footer].nil? Asciidoctor.render(@data, @options) end tilt-2.4.0/lib/tilt/babel.rb000066400000000000000000000004031463732220000156010ustar00rootroot00000000000000# frozen_string_literal: true 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.4.0/lib/tilt/builder.rb000066400000000000000000000014221463732220000161640ustar00rootroot00000000000000# frozen_string_literal: true 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.4.0/lib/tilt/cli.rb000066400000000000000000000101361463732220000153070ustar00rootroot00000000000000# 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.4.0/lib/tilt/coffee.rb000066400000000000000000000015561463732220000157750ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'coffee_script' module Tilt # CoffeeScript template implementation. See: # http://coffeescript.org/ # # CoffeeScript templates do not support object scopes, locals, or yield. 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.4.0/lib/tilt/commonmarker.rb000066400000000000000000000043471463732220000172410ustar00rootroot00000000000000# frozen_string_literal: true 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.4.0/lib/tilt/creole.rb000066400000000000000000000006041463732220000160100ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'creole' allowed_opts = [:allowed_schemes, :extensions, :no_escape].freeze # Creole implementation. See: http://www.wikicreole.org/ Tilt::CreoleTemplate = Tilt::StaticTemplate.subclass do opts = {} allowed_opts.each do |k| opts[k] = @options[k] if @options[k] end Creole::Parser.new(@data, opts).to_html end tilt-2.4.0/lib/tilt/csv.rb000066400000000000000000000021211463732220000153260ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'csv' module Tilt # CSV Template implementation. See: # http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html # # == 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) # 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.4.0/lib/tilt/erb.rb000066400000000000000000000027441463732220000153160ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'erb' module Tilt # ERB template implementation. See: # http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html 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.4.0/lib/tilt/erubi.rb000066400000000000000000000036031463732220000156470ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'erubi' module Tilt # Erubi (a simplified version of Erubis) template implementation. # See https://github.com/jeremyevans/erubi # # 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). 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.4.0/lib/tilt/erubis.rb000066400000000000000000000032301463732220000160260ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'erb' require 'erubis' warn 'tilt/erubis is deprecated, as erubis requires modifying string literals', uplevel: 1 module Tilt # Erubis template implementation. See: # http://www.kuwata-lab.com/erubis/ # # ErubisTemplate supports the following additional options, which are not # passed down to the Erubis engine: # # :engine_class allows you to specify a custom engine class to use # instead of the default (which is ::Erubis::Eruby). # # :escape_html when true, ::Erubis::EscapedEruby will be used as # the engine class instead of the default. All content # within <%= %> blocks will be automatically html escaped. class ErubisTemplate < ERBTemplate def prepare @freeze_string_literals = !!@options.delete(:freeze) @outvar = @options.delete(:outvar) || '_erbout' @options[:preamble] = false @options[:postamble] = false @options[:bufvar] = @outvar engine_class = @options.delete(:engine_class) engine_class = ::Erubis::EscapedEruby if @options.delete(:escape_html) @engine = (engine_class || ::Erubis::Eruby).new(@data, @options) end def precompiled_preamble(locals) [super, "#{@outvar} = _buf = String.new"].join("\n") end def precompiled_postamble(locals) [@outvar, super].join("\n") end # Erubis doesn't have ERB's line-off-by-one under 1.9 problem. # Override and adjust back. def precompiled(locals) source, offset = super [source, offset - 1] end def freeze_string_literals? @freeze_string_literals end end end tilt-2.4.0/lib/tilt/etanni.rb000066400000000000000000000011571463732220000160210ustar00rootroot00000000000000# frozen_string_literal: true 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.4.0/lib/tilt/haml.rb000066400000000000000000000057651463732220000154750ustar00rootroot00000000000000# frozen_string_literal: true 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.4.0/lib/tilt/kramdown.rb000066400000000000000000000006631463732220000163660ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'kramdown' dumb_quotes = [39, 39, 34, 34].freeze # Kramdown Markdown implementation. See: https://kramdown.gettalong.org/ 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.4.0/lib/tilt/liquid.rb000066400000000000000000000022541463732220000160310ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'liquid' module Tilt # Liquid template implementation. See: # http://liquidmarkup.org/ # # 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. # # It's suggested that your program require 'liquid' at load # time when using this template engine. 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.4.0/lib/tilt/livescript.rb000066400000000000000000000005501463732220000167230ustar00rootroot00000000000000# frozen_string_literal: true require_relative 'template' require 'livescript' # LiveScript template implementation. See: # http://livescript.net/ # # LiveScript templates do not support object scopes, locals, or yield. Tilt::LiveScriptTemplate = Tilt::StaticTemplate.subclass(mime_type: 'application/javascript') do LiveScript.compile(@data, @options) end tilt-2.4.0/lib/tilt/mapping.rb000066400000000000000000000324721463732220000162020ustar00rootroot00000000000000# 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