Ruby embedded in html

ERB – Ruby Templating ¶ ↑

ERB provides an easy to use but powerful templating system for Ruby. Using ERB , actual Ruby code can be added to any plain text document for the purposes of generating document information details and/or flow control.

A very simple example is this:

require 'erb' x = 42 template = ERB.new   The value of x is: EOF puts template.result(binding)

Prints: The value of x is: 42

More complex examples are given below.

Recognized Tags ¶ ↑

ERB recognizes certain tags in the provided template and converts them based on the rules below:

   (` (optional -- see ERB.new) %% replaced with % if first thing on a line and % processing is used -- replace with respectively

All other text is passed through ERB filtering unchanged.

Options ¶ ↑

There are several settings you can change when you use ERB:

  • the nature of the tags that are recognized;
  • the binding used to resolve local variables in the template.

See the ERB.new and ERB#result methods for more detail.

Character encodings ¶ ↑

ERB (or Ruby code generated by ERB ) returns a string in the same character encoding as the input string. When the input string has a magic comment, however, it returns a string in the encoding specified by the magic comment.

# -*- coding: utf-8 -*- require 'erb' template = ERB.new   \_\_ENCODING\_\_ is . EOF puts template.result 

Prints: _ENCODING_ is Big5.

Examples ¶ ↑

Plain Text ¶ ↑

ERB is useful for any generic templating situation. Note that in this example, we use the convenient “% at start of line” tag, and we quote the template literally with %q <. >to avoid trouble with the backslash.

require "erb" # Create template. template = %q < From: James Edward Gray II To: Subject: Addressing Needs : Just wanted to send a quick note assuring that your needs are being addressed. I want you to know that my team will keep working on the issues, especially: % priorities.each do |priority| * % end Thanks for your patience. James Edward Gray II >.gsub(/^ /, '') message = ERB.new(template, trim_mode: "%<>") # Set up template data. to = "Community Spokesman " priorities = [ "Run Ruby Quiz", "Document Modules", "Answer Questions on Ruby Talk" ] # Produce result. email = message.result puts email 
From: James Edward Gray II To: Community Spokesman Subject: Addressing Needs Community: Just wanted to send a quick note assuring that your needs are being addressed. I want you to know that my team will keep working on the issues, especially: * Run Ruby Quiz * Document Modules * Answer Questions on Ruby Talk Thanks for your patience. James Edward Gray II

Ruby in HTML ¶ ↑

ERB is often used in .rhtml files (HTML with embedded Ruby). Notice the need in this example to provide a special binding when the template is run, so that the instance variables in the Product object can be resolved.

Generates (some blank lines removed):

  • Listens for verbal commands in the Ruby language!
  • Ignores Perl, Java, and all C variants.
  • Karate-Chop Action.
  • Matz signature on left leg.
  • Gem studded eyes. Rubies, of course!

Notes ¶ ↑

There are a variety of templating solutions available in various Ruby projects. For example, RDoc , distributed with Ruby, uses its own template engine, which can be reused elsewhere.

Other popular engines could be found in the corresponding Category of The Ruby Toolbox.

Constants

Attributes

The optional filename argument passed to Kernel#eval when the ERB code is run

The optional lineno argument passed to Kernel#eval when the ERB code is run

The Ruby code generated by ERB

Public Class Methods

new (str, safe_level=NOT_GIVEN, legacy_trim_mode=NOT_GIVEN, legacy_eoutvar=NOT_GIVEN, trim_mode: nil, eoutvar: ‘_erbout’) click to toggle source

Constructs a new ERB object with the template specified in str.

An ERB object works by building a chunk of Ruby code that will output the completed template when run.

If trim_mode is passed a String containing one or more of the following modifiers, ERB will adjust its code generation as listed:

% enables Ruby code processing for lines beginning with % <> omit newline for lines starting with > omit newline for lines ending in %> - omit blank lines ending in -%>

eoutvar can be used to set the name of the variable ERB will build up its output in. This is useful when you need to run multiple ERB templates through the same binding and/or when you want to control where output ends up. Pass the name of the variable to be used inside a String .

Example ¶ ↑

require "erb" # build data class class Listings PRODUCT = < :name => "Chicken Fried Steak", :desc => "A well messages pattie, breaded and fried.", :cost => 9.95 > attr_reader :product, :price def initialize( product = "", price = "" ) @product = product @price = price end def build b = binding # create and run templates, filling member data variables ERB.new(, trim_mode: "", eoutvar: "@product").result b   END_PRODUCT ERB.new(, trim_mode: "", eoutvar: "@price").result b  --  END_PRICE end end # setup template data listings = Listings.new listings.build puts listings.product + "\n" + listings.price 
Chicken Fried Steak A well messages pattie, breaded and fried. Chicken Fried Steak -- 9.95 A well messages pattie, breaded and fried.
# File lib/erb.rb, line 334 def initialize(str, safe_level=NOT_GIVEN, legacy_trim_mode=NOT_GIVEN, legacy_eoutvar=NOT_GIVEN, trim_mode: nil, eoutvar: '_erbout') # Complex initializer for $SAFE deprecation at [Feature #14256]. Use keyword arguments to pass trim_mode or eoutvar. if safe_level != NOT_GIVEN warn 'Passing safe_level with the 2nd argument of ERB.new is deprecated. Do not use it, and specify other arguments as keyword arguments.', uplevel: 1 end if legacy_trim_mode != NOT_GIVEN warn 'Passing trim_mode with the 3rd argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, trim_mode: . ) instead.', uplevel: 1 trim_mode = legacy_trim_mode end if legacy_eoutvar != NOT_GIVEN warn 'Passing eoutvar with the 4th argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, eoutvar: . ) instead.', uplevel: 1 eoutvar = legacy_eoutvar end compiler = make_compiler(trim_mode) set_eoutvar(compiler, eoutvar) @src, @encoding, @frozen_string = *compiler.compile(str) @filename = nil @lineno = 0 @_init = self.class.singleton_class end

Returns revision information for the erb.rb module.

Источник

Embedding Ruby in html

So far we’ve looked at using Ruby to create HTML output, but we can turn the problem inside out; we can actually embed Ruby in an HTML document.

There are a number of packages that allow you to embed Ruby statements in some other sort of a document, especially in an HTML page. Generically, this is known as «eRuby.» Specifically, there are several different implementations of eRuby, including erubyanderb. The remainder of this section will discusseruby, written by Shugo Maeda.

Embedding Ruby in HTML is a very powerful concept—it basically gives us the equivalent of a tool such as ASP, JSP, or PHP, but with the full power of Ruby.

Using eruby

erubyacts as a filter, plain and simple. Any text within the input file is passed through untouched, with the following exceptions:

The Ruby code between the delimiters is replaced with its output.

The Ruby expression between the delimiters is replaced with its value.

The Ruby code between the delimiters is ignored (useful for testing).

If the documentis omitted,erubywill read from standard input. The command-line options forerubyare shown in Table 14.1 on page 149.

Command-line options for eruby

Specifies an alternate coding system (see page 137).

Specifies runtime mode, one of:

CGI mode (prints errors as HTML, sets $SAFE=1)

NPH-CGI mode (prints extra HTTP headers, sets $SAFE=1)

Disables CGI header output.

Prints version information and exits.

Let’s look at some simple examples. We’ll run the erubyexecutable on the following input.

This text is

erubysubstitutes the expression between the delimiters and produces

This text is almost degrees! Cool!

replaces the =awith the value ofa.

This text is almost 100 degrees! Cool!

And, of course, you can embed Ruby within a more complex document type, such as HTML.

Источник

Читайте также:  Finding file extension in python
Оцените статью