Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ruby / Yukihiro Matsumoto_Programming Ruby.doc
Скачиваний:
122
Добавлен:
06.06.2015
Размер:
2.71 Mб
Скачать

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:

Expression

Description

<%ruby code%>

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

<%=ruby expression%>

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

<%#ruby code%>

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

You invoke erubyas:

eruby [

options

][

document

]

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

Option

Description

-d,--debug

Sets $DEBUG to true.

-Kkcode

Specifies an alternate coding system (see page 137).

-Mmode

Specifies runtime mode, one of:

f

filter mode

c

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

n

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

-n,--noheader

Disables CGI header output.

-v,--verbose

Enables verbose mode.

--version

Prints version information and exits.

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

This text is <% a = 100; puts "#{a}% Live!" %>

erubysubstitutes the expression between the delimiters and produces

This text is 100% Live!

Using the <%= form acts as if you printed the value of the expression. For instance, the input

<%a = 100%>This text is almost <%=a%> 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.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<html>

<head>

<title>eruby example</title>

</head>

<body>

<h1>Enumeration</h1>

<ul>

<%(1..10).each do|i|%>

  <li>number <%=i%></li>

<%end%>

</ul>

<h1>Environment variables</h1>

<table>

<%ENV.keys.sort.each do |key|%>

  <tr>

    <th><%=key%></th><td><%=ENV[key]%></td>

  </tr>

<%end%>

</table>

</body>

</html>

Соседние файлы в папке Ruby