Revert e9d392b56a9dbde39fbbd6d8831e8933d53c3f5e ... 0f2c63374b80c563867485809a204382462c3a2c on Liquid for Designers

etagwerker
2011-09-05 15:45:10 -07:00
parent 0f2c63374b
commit 347ce7289c
+131 -131
@@ -1,20 +1,20 @@
Hay dos tipos de tags en Liquid: De Texto y Lógicos. There are two types of markup in Liquid: Output and Tag.
* Tags de texto (que pueden devolver texto) están envueltos por * Output markup (which may resolve to text) is surrounded by
<pre> <pre>
{{ llaves dobles de apertura y cierre (se ven así) }} {{ matched pairs of curly brackets (ie, braces) }}
</pre> </pre>
* Tags lógicos (que nunca devuelven texto) están envueltos por * Tag markup (which cannot resolve to text) is surrounded by
<pre> <pre>
{% llave y porcentaje de apertura y cierre (se ven así) %} {% matched pairs of curly brackets and percent signs %}
</pre> </pre>
h1. Tags de Texto h1. Output
Aquí hay un ejemplo simple de salida: Here is a simple example of Output:
<pre> <pre>
Hello {{name}} Hello {{name}}
@@ -24,175 +24,176 @@ Hello {{ 'tobi' }}
<a name="filters"></a> <a name="filters"></a>
h2. Salida de Texto Avanzada: Filtros h2. Advanced output: Filters
Los tags de texto pueden tomar filtros. Output markup takes filters.
Los filtros son métodos simples. Filters are simple methods.
El primer parámetro que recibe el filtro es el texto o variable que se encuentra a la izquierda del filtro. The first parameter is always the output of the left side of the filter.
En caso de ver más de un filtro, lo que produzca el filtro más a la izquierda será el parámetro de entrada al filtro siguiente a la derecha. The return value of the filter will be the new left value when the next filter is run.
Cuando no haya más filtros, el template va a recibir el texto del último filtro aplicado. When there are no more filters, the template will receive the resulting string.
<pre> <pre>
Hola {{ 'tobi' | upcase }} Hello {{ 'tobi' | upcase }}
Hola tobi tiene {{ 'tobi' | size }} letras! Hello tobi has {{ 'tobi' | size }} letters!
Hola {{ '*tobi*' | textilize | upcase }} Hello {{ '*tobi*' | textilize | upcase }}
Hola {{ 'now' | date: "%Y %h" }} Hello {{ 'now' | date: "%Y %h" }}
</pre> </pre>
h3. Filtros Estándar h3. Standard Filters
* **date** - le dá formato a una fecha ("syntax reference":http://liquid.rubyforge.org/classes/Liquid/StandardFilters.html#M000012) * **date** - reformat a date ("syntax reference":http://liquid.rubyforge.org/classes/Liquid/StandardFilters.html#M000012)
* **capitalize** - Pone en mayúscula la primera letra del parámtro de entrada * **capitalize** - capitalize words in the input sentence
* **downcase** - Convierte todo el parámetro de entrada a minúsculas * **downcase** - convert an input string to lowercase
* **upcase** - Convierte todo el parámetro de entrada a mayúsculas * **upcase** - convert an input string to uppercase
* **first** - Devuelve el primer elemento de un parámetro de tipo array * **first** - get the first element of the passed in array
* **last** - Devuelve el último elemento de un parámetro de tipo array * **last** - get the last element of the passed in array
* **join** - Concatenar los elementos de un array con cierto caracter entre ellos * **join** - join elements of the array with certain character between them
* **sort** - Ordenar los elementos del array * **sort** - sort elements of the array
* **map** - Devuelve un array con la propiedad de los miembros de otro array * **map** - map/collect an array on a given property
* **size** - Devuelve el tamaño de un array o string (cadena de caracteres) * **size** - return the size of an array or string
* **escape** - Escapea un string * **escape** - escape a string
* **escape_once** - Devuelve una versión escapeada en html sin afectar entidades ya escapeadas * **escape_once** - returns an escaped version of html without affecting existing escaped entities
* **strip_html** - Saca todo html del string * **strip_html** - strip html from string
* **strip_newlines** - Saca todos los 'enters' (\n) de un string * **strip_newlines** - strip all newlines (\n) from string
* **newline_to_br** - Reemplaca todos los 'enters' (\n) con un HTML br * **newline_to_br** - replace each newline (\n) with html break
* **replace** - Reemplaza ocurrencias de cierto string **por ejemplo** {{ 'foofoo' | replace:'foo','bar' }} #=> 'barbar' * **replace** - replace each occurrence **e.g.** {{ 'foofoo' | replace:'foo','bar' }} #=> 'barbar'
* **replace_first** - Reemplaza la primer ocurrencia de un string **por ejemplo** {{ 'barbar' | replace_first:'bar','foo' }} #=> 'foobar' * **replace_first** - replace the first occurrence **e.g.** {{ 'barbar' | replace_first:'bar','foo' }} #=> 'foobar'
* **remove** - Remueve de un string toda ocurrencia de otro string **por ejemplo** {{ 'foobarfoobar' | remove:'foo' }} #=> 'barbar' * **remove** - remove each occurrence **e.g.** {{ 'foobarfoobar' | remove:'foo' }} #=> 'barbar'
* **remove_first** - Remueve de un string la primera ocurrencia de otro string **por ejemplo** {{ 'barbar' | remove_first:'bar' }} #=> 'bar' * **remove_first** - remove the first occurrence **e.g.** {{ 'barbar' | remove_first:'bar' }} #=> 'bar'
* **truncate** - Trunca un string de los X caracteres deseados * **truncate** - truncate a string down to x characters
* **truncatewords** - Trunca un string de las X palabras deseadas * **truncatewords** - truncate a string down to x words
* **prepend** - Concatena un string al principio de otro string **por ejemplo** {{ 'bar' | prepend:'foo' }} #=> 'foobar' * **prepend** - prepend a string **e.g.** {{ 'bar' | prepend:'foo' }} #=> 'foobar'
* **append** - Concatena un string al final de otro string **por ejemplo** {{ 'foo' | append:'bar' }} #=> 'foobar' * **append** - append a string **e.g.** {{ 'foo' | append:'bar' }} #=> 'foobar'
* **minus** - Resta un número de otro **por ejemplo** {{ 4 | minus:2 }} #=> 2 * **minus** - subtraction **e.g** {{ 4 | minus:2 }} #=> 2
* **plus** - Suma un número a otro **por ejemplo** {{ '1' | plus:'1' }} #=> '11', {{ 1 | plus:1 }} #=> 2 * **plus** - addition **e.g** {{ '1' | plus:'1' }} #=> '11', {{ 1 | plus:1 }} #=> 2
* **times** - Multiplica un número por otro **por ejemplo** {{ 5 | times:4 }} #=> 20 * **times** - multiplication **e.g** {{ 5 | times:4 }} #=> 20
* **divided_by** - Divide un número por otro **por ejemplo** {{ 10 | divided_by:2 }} #=> 5 * **divided_by** - division **e.g** {{ 10 | divided_by:2 }} #=> 5
* **split** - Divide un string utilizando un patrón parámetro **por ejemplo** {{ "a~b" | split:~ }} #=> ['a','b'] * **split** - split a string on a matching pattern **e.g.** {{ "a~b" | split:~ }} #=> ['a','b']
h1. Tags Lógicos h1. Tags
Se utilizan para la lógica dentro de tu template. Tags are used for the logic in your template.
Es muy fácil desarrollar nuevos tags, así que esperamos recibir nuevas contribuciones a esta librería. New tags are very easy to code, so I hope to get many contributions to the standard tag library after releasing this code.
Aquí hay una lista de tags: Here is a list of currently supported tags:
* **assign** - Assigna un valor a una variable * **assign** - Assgins some value to a variable
* **capture** - Captura texto dentro del bloque y lo guarda en una variable * **capture** - Block tag that captures text into a variable
* **case** - Se utiliza para hacer comparaciones con valores específico (bloque case...when) * **case** - Block tag, its the standard case...when block
* **comment** - Block tag, comenta el texto dentro del bloque * **comment** - Block tag, comments out the text in the block
* **cycle** - Se utiliza para ciclar entre valores, por ejemplo colores o clases DOM. * **cycle** - Cycle is usually used within a loop to alternate between values, like colors or DOM classes.
* **for** - Para ciclos tipo for * **for** - For loop
* **if** - Para bloques if/else estándar * **if** - Standard if/else block
* **include** - Incluye otro template, útil para templates parciales * **include** - Includes another template, useful for partials
* **unless** - Idéntico al if * **unless** - Mirror of if statement
h2. Comentarios h2. Comments
Comment es el tag más simple. Comment is the simplest tag.
Solamente oculta el contenido que encierra. It just swallows content.
<pre> <pre>
Generamos 1 millón de dólares {% comment %} en pérdidas {% endcomment %} este año We made 1 million dollars {% comment %} in losses {% endcomment %} this year
</pre> </pre>
h2. If / Else h2. If / Else
@if / else@ funciona como en cualquier lenguaje de programación. @if / else@ should be well known from any imaginable programming language.
Liquid te permite escribir expresiones simples en las clausulas del @if@ o @unless@ (y opcionalmente, @elsif@ y @else@): Liquid allows you to write simple expressions in the @if@ or @unless@ (and optionally, @elsif@ and @else@) clause:
<pre> <pre>
{% if user %} {% if user %}
Hola {{ user.name }} Hello {{ user.name }}
{% endif %} {% endif %}
{% if user.name == 'tobi' %} {% if user.name == 'tobi' %}
Hola tobi Hello tobi
{% elsif user.name == 'bob' %} {% elsif user.name == 'bob' %}
Hola bob Hello bob
{% endif %} {% endif %}
{% if user.name == 'tobi' or user.name == 'bob' %} {% if user.name == 'tobi' or user.name == 'bob' %}
Hola tobi o bob Hello tobi or bob
{% endif %} {% endif %}
{% if user.name == 'bob' and user.age > 45 %} {% if user.name == 'bob' and user.age > 45 %}
Hola viejo bob Hello old bob
{% endif %} {% endif %}
{% if user.name != 'tobi' %} {% if user.name != 'tobi' %}
Hola non-tobi Hello non-tobi
{% endif %} {% endif %}
# Es la misma clausula que la de arriba # Same as above
{% unless user.name == 'tobi' %} {% unless user.name == 'tobi' %}
Hola non-tobi Hello non-tobi
{% endunless %} {% endunless %}
# Fijarse si el user tiene creditcard # Check if the user has a credit card
{% if user.creditcard != null %} {% if user.creditcard != null %}
Pobre poor sob
{% endif %} {% endif %}
# Igual que arriba # Same as above
{% if user.creditcard %} {% if user.creditcard %}
Pobre poor sob
{% endif %} {% endif %}
# Chequear por un array vacío # Check for an empty array
{% if user.payments == empty %} {% if user.payments == empty %}
No pagaste todavía! you never paid !
{% endif %} {% endif %}
{% if user.age > 18 %} {% if user.age > 18 %}
Login aquí Login here
{% else %} {% else %}
Perdón, eres muy joven. Sorry, you are too young
{% endif %} {% endif %}
# array = 1,2,3 # array = 1,2,3
{% if array contains 2 %} {% if array contains 2 %}
el array incluye 2 array includes 2
{% endif %} {% endif %}
# string = 'hola mundo' # string = 'hello world'
{% if string contains 'hola' %} {% if string contains 'hello' %}
string incluye 'hello' string includes 'hello'
{% endif %} {% endif %}
</pre> </pre>
h2. Tag Case h2. Case Statement
Si necesita más condiciones, puede usar el tag @case@: If you need more conditions, you can use the @case@ statement:
<pre> <pre>
{% case condition %} {% case condition %}
{% when 1 %} {% when 1 %}
condition es 1 hit 1
{% when 2 or 3 %} {% when 2 or 3 %}
condition es 2 o 3 hit 2 or 3
{% else %} {% else %}
condition no es ni 1, ni 2, ni 3 ... else ...
{% endcase %} {% endcase %}
</pre> </pre>
*Ejemplo:* *Example:*
<pre> <pre>
{% case template %} {% case template %}
{% when 'label' %}
// {{ label.title }} {% when 'label' %}
{% when 'product' %} // {{ label.title }}
// {{ product.vendor | link_to_vendor }} / {{ product.title }} {% when 'product' %}
{% else %} // {{ product.vendor | link_to_vendor }} / {{ product.title }}
// {{page_title}} {% else %}
// {{page_title}}
{% endcase %} {% endcase %}
</pre> </pre>
h2. Tag Cycle h2. Cycle
Frecuentemente uno debe alternar entre colores diferentes o tareas similares. Often you have to alternate between different colors or similar tasks.
Liquid tiene soporte para ese tipo de operaciones, utilizando el tag @cycle@. Liquid has built-in support for such operations, using the @cycle@ tag.
<pre> <pre>
{% cycle 'one', 'two', 'three' %} {% cycle 'one', 'two', 'three' %}
@@ -200,7 +201,7 @@ Liquid tiene soporte para ese tipo de operaciones, utilizando el tag @cycle@.
{% cycle 'one', 'two', 'three' %} {% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %} {% cycle 'one', 'two', 'three' %}
va a producir: will result in
one one
two two
@@ -208,11 +209,11 @@ three
one one
</pre> </pre>
Si no se provee ningún nombre para el grupo del ciclo, If no name is supplied for the cycle group,
entonces se asume que múltiples llamadas con los mismos parámetros son un grupo. then it's assumed that multiple calls with the same parameters are one group.
Si quiere tener control total sobre los grupos del ciclo, opcionalmente puede especificar el nombre del grupo. If you want to have total control over cycle groups, you can optionally specify the name of the group.
Esto puede ser una variable. This can even be a variable.
<pre> <pre>
@@ -221,7 +222,7 @@ Esto puede ser una variable.
{% cycle 'group 2': 'one', 'two', 'three' %} {% cycle 'group 2': 'one', 'two', 'three' %}
{% cycle 'group 2': 'one', 'two', 'three' %} {% cycle 'group 2': 'one', 'two', 'three' %}
va a producir: will result in
one one
two two
@@ -229,9 +230,9 @@ one
two two
</pre> </pre>
h2. Ciclos For h2. For loops
Liquid te permite iterar sobre collecciones con un tag @for@: Liquid allows @for@ loops over collections:
<pre> <pre>
{% for item in array %} {% for item in array %}
@@ -239,22 +240,22 @@ Liquid te permite iterar sobre collecciones con un tag @for@:
{% endfor %} {% endfor %}
</pre> </pre>
En cada iteración del ciclo @for@, puede usar alguna de las siguientes variables para sus necesidades de styling: During every @for@ loop, the following helper variables are available for extra styling needs:
<pre> <pre>
forloop.length # => largo de todo el for forloop.length # => length of the entire for loop
forloop.index # => índice de la iteración actual (empieza en 1) forloop.index # => index of the current iteration
forloop.index0 # => índice de la iteración actual (empieza en 0) forloop.index0 # => index of the current iteration (zero based)
forloop.rindex # => cuántos items falta iterar? (empieza en 1) forloop.rindex # => how many items are still left?
forloop.rindex0 # => cuántos items falta iterar? (empieza en 0) forloop.rindex0 # => how many items are still left? (zero based)
forloop.first # => es esta la primera iteración? forloop.first # => is this the first iteration?
forloop.last # => es esta la última iteración? forloop.last # => is this the last iternation?
</pre> </pre>
Hay muchos atributos que puedes usar para influenciar a los items que usas para iterar en tu ciclo. There are several attributes you can use to influence which items you receive in your loop
*limit:int* te permite la cantidad de items que recibes para iterar. *limit:int* lets you restrict how many items you get.
*offset:int* te permite empezar en la posicion N de la collección. *offset:int* lets you start the collection with the nth item.
<pre> <pre>
# array = [1,2,3,4,5,6] # array = [1,2,3,4,5,6]
@@ -264,14 +265,14 @@ Hay muchos atributos que puedes usar para influenciar a los items que usas para
# results in 3,4 # results in 3,4
</pre> </pre>
Iterando el ciclo en forma inversa Reversing the loop
<pre> <pre>
{% for item in collection reversed %} {{item}} {% endfor %} {% for item in collection reversed %} {{item}} {% endfor %}
</pre> </pre>
En vez de iterar sobre una collección existente, puedes definir un rango de numbers para iterarlo. Instead of looping over an existing collection, you can define a range of numbers to loop through.
El rango se puede definir por literales o números variables: The range can be defined by both literal and variable numbers:
<pre> <pre>
# if item.quantity is 4... # if item.quantity is 4...
@@ -281,10 +282,10 @@ El rango se puede definir por literales o números variables:
# results in 1,2,3,4 # results in 1,2,3,4
</pre> </pre>
h2. Asignación de Variables h2. Variable Assignment
Puedes guardar datos en tus propias variables, para ser usadas en otros tags de texto o lógica como necesites. You can store data in your own variables, to be used in output or other tags as desired.
La forma más simple de crear una variable es con un tag @assign@, que tiene una sintáxis bien directa: The simplest way to create a variable is with the @assign@ tag, which has a pretty straightforward syntax:
<pre> <pre>
{% assign name = 'freestyle' %} {% assign name = 'freestyle' %}
@@ -294,7 +295,7 @@ La forma más simple de crear una variable es con un tag @assign@, que tiene una
{% endif %}{% endfor %} {% endif %}{% endfor %}
</pre> </pre>
Otra forma de hacer esto sería asignando los valores @true / false@ a una variable: Another way of doing this would be to assign @true / false@ values to the variable:
<pre> <pre>
{% assign freestyle = false %} {% assign freestyle = false %}
@@ -308,8 +309,7 @@ Otra forma de hacer esto sería asignando los valores @true / false@ a una varia
{% endif %} {% endif %}
</pre> </pre>
Si quieres combinar muchos strings en un solo string y luego guardarlo en una variable, puedes usar el tag @capture@. If you want to combine a number of strings into a single string and save it to a variable, you can do that with the @capture@ tag. This tag is a block which "captures" whatever is rendered inside it, then assigns the captured value to the given variable instead of rendering it to the screen.
Este tag es un bloque que "captura" todo lo que tenga adentro, luego lo asigna a una variable en vez de mostrarlo por pantalla.
<pre> <pre>
{% capture attribute_name %}{{ item.title | handleize }}-{{ i }}-color{% endcapture %} {% capture attribute_name %}{{ item.title | handleize }}-{{ i }}-color{% endcapture %}