diff --git a/sources/36-web2py-spanish-translation-in-progress/05.markmin b/sources/36-web2py-spanish-translation-in-progress/05.markmin index 5e0b5a42..475db358 100644 --- a/sources/36-web2py-spanish-translation-in-progress/05.markmin +++ b/sources/36-web2py-spanish-translation-in-progress/05.markmin @@ -1,92 +1,106 @@ -## The views +## Las vistas ``views``:inxx ``template language``:inxx ``HTML``:inxx -web2py uses Python for its models, controllers, and views, although it uses a slightly modified Python syntax in the views to allow more readable code without imposing any restrictions on proper Python usage. +web2py usa Python para sus modelos, controladores y vistas, aunque lo hace con una sintaxis levemente modificada en las vistas para permitir un código más legible, pero sin imponer restricciones al uso correcto del lenguaje. -The purpose of a view is to embed code (Python) in an HTML document. In general, this poses some problems: -- How should embedded code be escaped? -- Should indenting be based on Python or HTML rules? +El propósito de una vista es el de embeber código (Python) en un documento HTML. En general, esto trae algunos problemas: +- ¿Cómo debería realizarse el escapado del código embebido? +- ¿El espaciado debería responder a las normas de Python o a las de HTML? -web2py uses ``{{ ... }}`` to escape Python code embedded in HTML. The advantage of using curly brackets instead of angle brackets is that it's transparent to all common HTML editors. This allows the developer to use those editors to create web2py views. +web2py utiliza ``{{ ... }}`` para escapado de código Python embebido en HTML. La ventaja del uso de llaves en vez de corchetes es que los primeros son transparentes para los editores más utilizados. Esto permite al desarrollador el uso de esos editores para crear vistas de web2py. Los delimitadores se pueden cambiar por ejemplo con -Since the developer is embedding Python code into HTML, the document should be indented according to HTML rules, and not Python rules. Therefore, we allow unindented Python inside the ``{{ ... }}`` tags. Since Python normally uses indentation to delimit blocks of code, we need a different way to delimit them; this is why the web2py template language makes use of the Python keyword ``pass``. +`` +response.delimiters = ('') +``:code + +Si se agrega esa línea en el modelo se aplicará en toda la aplicación, si se agraga a un controlador sólo a las vistas asociadas a acciones de ese controlador, si se incluye en una acción sólo en la vista para esa acción. + +Como el desarrollador está embebiendo código Python en el HTML, se debería aplicar las reglas de espaciado de HTLM, no las reglas de Pyhton. Por lo tanto, permitimos código Python sin espaciado dentro de las etiquetas ``{{ ... }}``. Como Python normalmente usa espaciado para delimitar bloques de código, necesitamos una forma diferente para delimitarlos; es por eso que el lenguaje de plantillas hace uso de la palabra ``pass``. ------- -A code block starts with a line ending with a colon and ends with a line beginning with ``pass``. The keyword ``pass`` is not necessary when the end of the block is obvious from the context. +Un bloque de código comienza con una línea terminada con punto y coma y finaliza con una línea que comienza con ``pass``. La palabra ``pass`` no es necesaria cuando el final del bloque es obvio para su contexto. ------- -Here is an example: +Aquí hay un ejemplo: `` {{ if i == 0: -response.write('i is 0') +response.write('i es 0') else: -response.write('i is not 0') +response.write('i no es 0') pass }} ``:code -Note that ``pass`` is a Python keyword, not a web2py keyword. Some Python editors, such as Emacs, use the keyword ``pass`` to signify the division of blocks and use it to re-indent code automatically. +Ten en cuenta que ``pass`` es una palabra de Python, no de web2py. Algunos editores de Python, como Emacs, usan la palabra ``pass`` para señalar la división de bloques y la emplean en la modificación automática del espaciado. -The web2py template language does exactly the same. When it finds something like: +El lenguaje de plantillas de web2py hace exactamente lo mismo. Cuando encuentra algo como: `` -{{for x in range(10):}}{{=x}}hello
{{pass}} +{{for x in range(10):}}{{=x}}hola
{{pass}} ``:code -it translates it into a program: +lo traduce en un programa: + `` response.write("""""", escape=False) for x in range(10): response.write(x) - response.write("""hello
""", escape=False) + response.write("""hola
""", escape=False) response.write("""""", escape=False) ``:code -``response.write`` writes to the ``response.body``. -When there is an error in a web2py view, the error report shows the generated view code, not the actual view as written by the developer. This helps the developer debug the code by highlighting the actual code that is executed (which is something that can be debugged with an HTML editor or the DOM inspector of the browser). +``response.write`` escribe en ``response.body``. + +Cuando hay un error en una vista de web2py, el reporte del error muestra el código generado de la vista, no la vista real escrita por el desarrollador. Esto ayuda al desarrollador en la depuración del código resaltando la sección que se ejecuta (que se puede depurar con un editor de HTML o el inspector del DOM del navegador). + +Además, ten en cuenta que: -Also note that: `` {{=x}} ``:code -generates +genera + ``response.write``:inxx ``escape``:inxx `` response.write(x) ``:code -Variables injected into the HTML in this way are escaped by default. -The escaping is ignored if ``x`` is an ``XML`` object, even if escape is set to ``True``. +Las variables inyectadas en el HTML de esta forma se escapan por defecto. +El escapado es ignorado si ``x`` es un objeto ``XML``, incluso si se ha establecido escape como ``True``. + +Aquí hay un ejemplo que introduce el ayudante ``H1``: -Here is an example that introduces the ``H1`` helper: `` {{=H1(i)}} ``:code -which is translated to: +que se traduce como: + `` response.write(H1(i)) ``:code -upon evaluation, the ``H1`` object and its components are recursively serialized, escaped and written to the response body. The tags generated by ``H1`` and inner HTML are not escaped. This mechanism guarantees that all text --- and only text --- displayed on the web page is always escaped, thus preventing XSS vulnerabilities. At the same time, the code is simple and easy to debug. +al evaluarse, el objeto ``H1`` y sus componentes se serializan en forma recursiva, se escapan y escriben en el cuerpo de la respuesta. Las etiquetas generadas por ``H1`` y el HTML incluído no se escapan. Este mecanismo garantiza que el texto -- y sólo el texto -- mostrado en la página web se escapa siempre, previniendo de esa forma vulnerabilidades XSS. Al mismo tiempo, el código es simple y fácil de depurar. + -The method ``response.write(obj, escape=True)`` takes two arguments, the object to be written and whether it has to be escaped (set to ``True`` by default). If ``obj`` has an ``.xml()`` method, it is called and the result written to the response body (the ``escape`` argument is ignored). Otherwise it uses the object's ``__str__`` method to serialize it and, if the escape argument is ``True``, escapes it. All built-in helper objects (``H1`` in the example) are objects that know how to serialize themselves via the ``.xml()`` method. +El método ``response.write(obj, escape=True)`` toma dos argumentos, el objeto a escribirse y si se debe escapar (con valor ``True`` por defecto). Si ``obj`` tiene un método ``.xml()``, se llama y el resultado se escribe en el cuerpo de la respuesta (el argumento ``escape`` se ignora). De lo contrario, usa el método ``__str__`` del objeto para serializarlo y, si el argumento escape es ``True``, lo escapa. Todos los ayudantes incorporados (``H1`` por ejemplo) son objetos que saben cómo serializarse a sí mismos a través del método ``.xml()``. -This is all done transparently. You never need to (and never should) call the ``response.write`` method explicitly. +Todo esto se hace en forma transparente. Nunca necesitas (y nunca deberías) llamar al método ``response.write`` en forma explícita. -### Basic syntax +### Sintaxis básica -The web2py template language supports all Python control structures. Here we provide some examples of each of them. They can be nested according to usual programming practice. +El lenguaje de plantillas de web2py soporta todas las estructuras de control de Python. Aquí damos algunos ejemplos de cada uno. Se pueden anidar según las convenciones usuales de programación. #### ``for...in`` ``for``:inxx -In templates you can loop over any iterable object: +En plantillas puedes realizar bucles de objetos iterable: + `` {{items = ['a', 'b', 'c']}} ``:code -which produces: +que produce: + `` ``:code -Here ``item`` is any iterable object such as a Python list, Python tuple, or Rows object, or any object that is implemented as an iterator. The elements displayed are first serialized and escaped. +Aquí ``items`` es todo iterable como por ejemplo un list o tuple de Python o un objeto Rows, o cualquier objeto que implemente un iterator. Los elementos mostrados son previamente serializados y escapados. #### ``while`` ``while``:inxx -You can create a loop using the while keyword: +Para crear un bucle puedes usar la palabra while: `` {{k = 3}} ``:code -which produces: +que produce: + `` ``:code -It produces exactly the same output as above. In this case, the function ``itemize2`` represents a piece of HTML that is going to replace the web2py tag where the function is called. Notice that there is no '=' in front of the call to ``itemize2``, since the function does not return the text, but it writes it directly into the response. +Este produce exactamente la misma salida que arriba. En este caso la función ``itemize2`` representa una sección de HTML que va a reemplazar la etiqueta de web2py donde se ha llamado a la función. Ten en cuenta que no hay '=' delante de la llamada a ``itemize2``, ya que la función no devuelve el texto, sino que lo escribe directamente en la respuesta. -There is one caveat: functions defined inside a view must terminate with a return statement, or the automatic indentation will fail. +Hay un detalle: las funciones definidas dentro de una vista deben terminar con una instrucción return, o el espaciado automático fallará. -### HTML helpers +### Ayudantes HTML ``helpers``:inxx +Si tenemos el siguiente código en una vista Consider the following code in a view: `` -{{=DIV('this', 'is', 'a', 'test', _id='123', _class='myclass')}} +{{=DIV('esta', 'es', 'una', 'prueba', _id='123', _class='miclase')}} ``:code -it is rendered as: +este se procesa como: `` -
thisisatest
+
estaesunaprueba
``:code -``DIV`` is a helper class, i.e., something that can be used to build HTML programmatically. It corresponds to the HTML ``
`` tag. -Positional arguments are interpreted as objects contained between the open and close tags. Named arguments that start with an underscore are interpreted as HTML tag attributes (without the underscore). Some helpers also have named arguments that do not start with underscore; these arguments are tag-specific. +``DIV`` es una clase ayudante, es decir, algo que se puede usar para armar HTML en forma programática. Se corresponde con la etiqueta ``
`` de HTML. + +Los argumentos posicionales se interpretan como objetos contenidos entre las etiquetas de apertura y cierre. Los pares nombre-valor o (named argument) que comienzan con subguión son interpretados como atributos HTML (sin subguión). Algunos ayudantes también tienen pares nombre-valor que no comienzan con subguión; estos valores son específicos de la etiqueta HTML. + +En lugar de un conjunto de argumentos sin nombre, un ayudante puede también tomar una lista o tupla como conjunto de componentes usando la notación ``*`` y puede tomar un diccionario como conjunto de atributos usando ``**``, por ejemplo: -Instead of a set of unnamed arguments, a helper can also take a single list or tuple as its set of components using the ``*`` notation and it can take a single dictionary as its set of attributes using the ``**``, for example: `` {{ -contents = ['this','is','a','test'] -attributes = {'_id':'123', '_class':'myclass'} -=DIV(*contents,**attributes) +contenido = ['este','es','un','prueba'] +atributos = {'_id':'123', '_class':'miclase'} +=DIV(*contenido,**atributos) }} ``:code -(produces the same output as before). +(genera la misma salida que antes). -The following set of helpers: +La siguiente lista de ayudantes: ``A``, ``B``, ``BEAUTIFY``, ``BODY``, ``BR``, ``CAT``, ``CENTER``, ``CODE``, ``COL``, ``COLGROUP``, ``DIV``, ``EM``, ``EMBED``, ``FIELDSET``, ``FORM``, ``H1``, ``H2``, ``H3``, ``H4``, ``H5``, ``H6``, ``HEAD``, ``HR``, ``HTML``, ``I``, ``IFRAME``, ``IMG``, ``INPUT``, ``LABEL``, ``LEGEND``, ``LI``, ``LINK``, ``MARKMIN``, ``MENU``, ``META``, ``OBJECT``, ``ON``, ``OL``, ``OPTGROUP``, ``OPTION``, ``P``, ``PRE``, ``SCRIPT``, ``SELECT``, ``SPAN``, ``STYLE``, ``TABLE``, ``TAG``, ``TBODY``, ``TD``, ``TEXTAREA``, ``TFOOT``, ``TH``, ``THEAD``, ``TITLE``, ``TR``, ``TT``, ``UL``, ``URL``, ``XHTML``, ``XML``, ``embed64``, ``xmlescape`` -can be used to build complex expressions that can then be serialized to XML``xml-w``:cite ``xml-o``:cite. For example: +se puede usar para construir expresiones complejas que se pueden serializar como XML``xml-w``:cite ``xml-o``:cite. Por ejemplo: + `` -{{=DIV(B(I("hello ", ""))), _class="myclass")}} +{{=DIV(B(I("hola ", ""))), _class="miclase")}} ``:code -is rendered: +produce: `` -
hello <world>
+
hola <mundo>
``:code -Helpers can also be serialized into strings, equivalently, with the ``__str__`` and the ``xml`` methods: +Los ayudantes también pueden serializarse como cadenas, indistintamente, con los métodos ``__str__`` y ``xml``: `` ->>> print str(DIV("hello world")) -
hello world
->>> print DIV("hello world").xml() -
hello world
+>>> print str(DIV("hola mundo")) +
hola mundo
+>>> print DIV("hola mundo").xml() +
hola mundo
`` ``Document Object Model (DOM)``:inxx -The helpers mechanism in web2py is more than a system to generate HTML without concatenating strings. It provides a server-side representation of the Document Object Model (DOM). +El mecanismo de ayudantes en web2py es más que un sistema para generar HTML sin métodos de concatenación. Este provée una representación del lado del servidor del Document Object Model (DOM). + +Los componentes de los ayudantes se pueden recuperar por su posición, y los ayudantes funcionan como listas con respecto a sus componentes: -Components of helpers can be referenced via their position, and helpers act as lists with respect to their components: `` >>> a = DIV(SPAN('a', 'b'), 'c') >>> print a @@ -294,7 +322,7 @@ Components of helpers can be referenced via their position, and helpers act as l
ybx
``:code -Attributes of helpers can be referenced by name, and helpers act as dictionaries with respect to their attributes: +Los atributos de los ayudantes se pueden recuperar por nombre, y los ayudantes funcionan como diccionarios con respecto a sus atributos: `` >>> a = DIV(SPAN('a', 'b'), 'c') >>> a['_class'] = 's' @@ -303,62 +331,68 @@ Attributes of helpers can be referenced by name, and helpers act as dictionaries
abc
``:code -Note, the complete set of components can be accessed via a list called ``a.components``, and the complete set of attributes can be accessed via a dictionary called ``a.attributes``. So, ``a[i]`` is equivalent to ``a.components[i]`` when ``i`` is an integer, and ``a[s]`` is equivalent to ``a.attributes[s]`` when ``s`` is a string. +Ten en cuenta que el conjunto completo de componentes puede recuperarse a través de una lista llamada ``a.components``, y el conjunto completo de atributos se puede recuperar a través de un diccionario llamado ``a.attributes``. Por lo que, ``a[i]`` equivale a ``a.components[i]`` cuando ``i`` es un entero, y ``a[s]`` es equivalente a ``a.attributes[s]`` cuando ``s`` es una cadena. -Notice that helper attributes are passed as keyword arguments to the helper. In some cases, however, attribute names include special characters that are not allowed in Python identifiers (e.g., hyphens) and therefore cannot be used as keyword argument names. For example: +Observa que los atributos de ayudantes se pasan como pares de argumentos nombre-valor (named arguments) al ayudante. En algunos casos, sin embargo, los nombres de atributos incluyen caracteres especiales que no son elementos válidos en variables de Python (por ejemplo, los guiones) y por lo tanto no se pueden usar en pares de argumentos nombre-valor. Por ejemplo: `` DIV('text', _data-role='collapsible') ``:code -will not work because "_data-role" includes a hyphen, which will produce a Python syntax error. +No funcionará porque "_data-role" incluye un guión, que produciría un error sintáctico de Python. -In such cases, you can instead pass the attributes as a dictionary and make use of Python's ``**`` function arguments notation, which map a dictionary of (key:value) pairs into a set of keyword arguments: +En esos casos, sin embargo, puedes pasar los atributos como un diccionario y utilizar la notación ``**`` para argumentos de función, que asocia un diccionario de pares (nombre:valor) a un conjunto de pares de argumentos nombre-valor. `` >>> print DIV('text', **{'_data-role': 'collapsible'})
text
``:code -You can also dynamically create special TAGs: +También puedes crear etiquetas (TAG) especiales en forma dinámica: `` ->>> print TAG['soap:Body']('whatever',**{'_xmlns:m':'http://www.example.org'}) -whatever +>>> print TAG['soap:Body']('algo',**{'_xmlns:m':'http://www.example.org'}) +algo ``:code #### ``XML`` ``XML``:inxx -``XML`` is an object used to encapsulate text that should not be escaped. The text may or may not contain valid XML. For example, it could contain JavaScript. -The text in this example is escaped: +``XML`` es un objeto que se utiliza para encapsular texto que no debería escaparse. El texto puede o no contener XML válido. Por ejemplo, puede contener JavaScript. + +El texto de este ejemplo se escapa: + `` ->>> print DIV("hello") -<b>hello</b> +>>> print DIV("hola") +<b>hola</b> ``:code -by using ``XML`` you can prevent escaping: +con el uso de ``XML`` puedes prevenir el escapado: `` ->>> print DIV(XML("hello")) -hello +>>> print DIV(XML("hola")) +hola ``:code -Sometimes you want to render HTML stored in a variable, but the HTML may contain unsafe tags such as scripts: +A veces puedes necesitar convertir HTML almacenado en una variable, pero el HTML puede contener etiquetas inseguras como scripts: + `` ->>> print XML('') - +>>> print XML('') + ``:code -Un-escaped executable input such as this (for example, entered in the body of a comment in a blog) is unsafe, because it can be used to generate Cross Site Scripting (XSS) attacks against other visitors to the page. +Código ejecutable sin escapado como este (por ejemplo, ingresado en el cuerpo de un comentario de un blog) no es seguro, porque puede ser usado para generar un ataque de tipo Cross Site Scripting (XSS) en perjuicio de otros usuarios de la página. ``sanitize``:inxx -The web2py ``XML`` helper can sanitize our text to prevent injections and escape all tags except those that you explicitly allow. Here is an example: + +El ayudante ``XML`` puede sanitizar nuestro texto para prevenir inyecciones y escapar todas las etiquetas excepto aquellas que explícitamente permitas. Aquí hay un ejemplo: + `` ->>> print XML('', sanitize=True) -<script>alert("unsafe!")</script> +>>> print XML('', sanitize=True) +<script>alert("no es seguro!")</script> ``:code -The ``XML`` constructors, by default, consider the content of some tags and some of their attributes safe. You can override the defaults using the optional ``permitted_tags`` and ``allowed_attributes`` arguments. Here are the default values of the optional arguments of the ``XML`` helper. +El constructor de ``XML``, por defecto, considera los contenidos de algunas etiquetas y algunos de sus atributos como seguros. Puedes modificar los valores por defecto con los argumentos opcionales ``permitted_tags`` y ``allowed_attributes``. Estos son los valores por defecto de los argumentos opcionales para el ayudante ``XML``. + `` XML(text, sanitize=False, permitted_tags=['a', 'b', 'blockquote', 'br/', 'i', 'li', @@ -367,112 +401,128 @@ XML(text, sanitize=False, 'img':['src', 'alt'], 'blockquote':['type']}) ``:code -#### Built-in helpers +#### Ayudantes incorporados ##### ``A`` -This helper is used to build links. +Este ayudante se usa para generar vínculos (links). ``A``:inxx `` ->>> print A('', XML('me'), +>>> print A('', XML('aquí'), _href='http://www.web2py.com') -<click>me/b> +<haz clic>aquí ``:code -Instead of ``_href`` you can pass the URL using the ``callback`` argument. For example in a view: +En lugar de ``_href`` puedes pasar el URL usando el argumento ``callback``. Por ejemplo en una vista: `` -{{=A('click me', callback=URL('myaction'))}} +{{=A('haz clic aquí', callback=URL('miaccion'))}} `` -and the effect of pressing the link will be an ajax call to "myaction" instead of a redirection. -In this case, optionally you can specify two more arguments: ``target`` and ``delete``: +y el resultado de hacer clic en el link será una llamada ajax a "miaccion" en lugar de una redirección. + +En este caso, opcionalmente se pueden especificar dos argumentos más: ``target`` y ``delete``: + `` -{{=A('click me', callback=URL('myaction'), target="t")}} +{{=A('clic aquí', callback=URL('miaccion'), target="t")}}
`` -and the response of the ajax callback will be stored in the DIV with id equal to "t". + +y la respuesta de la llamada ajax será almacenada en el DIV con el id igual a "t". `` -
{{=A('click me', callback=URL('myaction'), delete='div#b")}}
+
{{=A('clic aquí', callback=URL('miaccion'), delete='div#b")}}
`` -and upon response, the closest tag matching "div#b" will be deleted. In this case, the button will be deleted. -A typical application is: + +y al recibir la respuesta, la etiqueta más próxima que coincida con "div#b" se eliminará. En este caso, el botón será eliminado. +Una aplicación típica es: `` -{{=A('click me', callback=URL('myaction'), delete='tr")}} +{{=A('clic aquí', callback=URL('miaccion'), delete='tr")}} `` -in a table. Pressing the button will perform the callback and delete the table row. +en una tabla. Presionanado el botón se ejecutará el callback y se eliminará el registro de la tabla. Se pueden combinar ``callback`` y ``delete`` -``callback`` and ``delete`` can be combined. - -Tha A helper takes a special argument called ``cid``. It works as follows: +El ayudante A toma un argumento especial llamado ``cid``. Funciona de la siguiente forma: `` -{{=A('linked page', _href='http://example.com', cid='myid')}} -
+{{=A('página del link', _href='http://example.com', cid='miid')}} +
``:code -and a click on the link causes the content to be loaded in the div. This is similar but more powerful than the above syntax since it is designed to refresh page components. We discuss applications of ``cid`` in more detail in Chapter 12, in the context of components. +y hacer clic en el link hace que el contenido se cargue en el div. Esto es parecido pero más avanzado que la sintaxis de arriba ya que se ha diseñado para que refresque los componentes de la página. Las aplicaciones de ``cid`` se tratarán con más detalle en el capítulo 12, en relación con el concepto de componente. + -These ajax features require jQuery and "static/js/web2py_ajax.js", which are automatically included by placing ``{{include 'web2py_ajax.html'}}`` in the layout head. "views/web2py_ajax.html" defines some variables based on ``request`` and includes all necessary js and css files. +Estas funcionalidades ajax requieren jQuery y "static/js/web2py.js", que se incluyen automáticamente al agregar ``{{'web2py_ajax.html'}}`` la sección head de la plantilla general (layout). "views/web2py_ajax.html" define algunas variables basadas en ``request`` e incluye todos los archivos js y css necesarios. ##### ``B`` ``B``:inxx -This helper makes its contents bold. +Este ayudante hace que su contenido sea en negrita. + `` ->>> print B('', XML('world'), _class='test', _id=0) -<hello>world +>>> print B('', XML('mundo'), _class='prueba', _id=0) +<hola>mundo ``:code ##### ``BODY`` ``BODY``:inxx -This helper makes the body of a page. + +Este ayudante crea el cuerpo de una página. + `` ->>> print BODY('', XML('world'), _bgcolor='red') -<hello>world +>>> print BODY('', XML('mundo'), _bgcolor='red') +<hola>mundo ``:code ##### ``BR`` ``BR``:inxx -This helper creates a line break. +Este ayudante crea un salto de línea. + `` >>> print BR()
``:code -##### ``CAT`` (1.98.1 and up) +Ten en cuenta que los ayudantes se pueden repetir utilizando el operador de multiplicación: + +`` +>>> print BR()*5 +




+``:code + +##### ``CAT`` ``CAT``:inxx -This helper concatenates other helpers, same as TAG['']. +Este es un ayudante que realiza concatenación de otros ayudantes, análogo a TAG['']. + `` ->>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.') -Here is a link, and here is some bold text. +>>> print CAT('Aquí tenemos ', A('link',_href=URL()), ', y aquí hay un poco de ', B('texto en negrita'), '.') +Aquí tenemos link, y aquí hay un poco de texto en negrita. ``:code ##### ``CENTER`` ``CENTER``:inxx -This helper centers its content. +Este ayudante centra su contenido. + `` ->>> print CENTER('', XML('world'), ->>> _class='test', _id=0) -
<hello>world
+>>> print CENTER('', XML('mundo'), +>>> _class='prueba', _id=0) +
<hola>mundo
``:code ##### ``CODE`` ``CODE``:inxx -This helper performs syntax highlighting for Python, C, C++, HTML and web2py code, and is preferable to ``PRE`` for code listings. ``CODE`` also has the ability to create links to the web2py API documentation. +Este ayudante resalta la sintaxis para Python, C, C++, HTML y código web2py, y se recomienda en lugar de ``PRE`` para muestras de código. ``CODE`` también tiene la funcionalidad de crear links a la documentación de la API de web2py. -Here is an example of highlighting sections of Python code. +Este es un ejemplo de resaltado de una sección de código fuente Python. `` ->>> print CODE('print "hello"', language='python').xml() +>>> print CODE('print "hola"', language='python').xml() + "hola"
print 
-    "hello"
``:code -Here is a similar example for HTML +Aquí hay un ejemplo similar para HTML + `` >>> print CODE( >>> '{{=request.env.remote_add}}', @@ -507,24 +558,25 @@ Here is a similar example for HTML ...... ``:code -These are the default arguments for the ``CODE`` helper: +Estos son los argumentos por defecto para el ayudante ``CODE``: + `` -CODE("print 'hello world'", language='python', link=None, counter=1, styles={}) +CODE("print 'hola mundo'", language='python', link=None, counter=1, styles={}) ``:code -Supported values for the ``language`` argument are "python", "html_plain", "c", "cpp", "web2py", and "html". The "html" language interprets {{ and }} tags as "web2py" code, while "html_plain" doesn't. +Los valores soportados para el argumento ``language`` son "python", "html_plain", "c", "cpp", "web2py", y "html". El lenguaje interpreta etiquetas {{ y }} como código "web2py", mientras que "html_plain" no lo hace. -If a ``link`` value is specified, for example "/examples/global/vars/", web2py API references in the code are linked to documentation at the link URL. For example "request" would be linked to "/examples/global/vars/request". In the above example, the link URL is handled by the "vars" action in the "global.py" controller that is distributed as part of the web2py "examples" application. +Si se especifica un valor ``link``, por ejemplo "/examples/global/vars/", las referencias a la API de web2py en el código se vinculan con la documentación en el URL del link. Por ejemplo, "request" se asociaría a "/examples/global/vars/request". En el ejemplo de arriba, el URL del link es manejado por la acción "vars" en el controlador "global.py" que se distribuye como parte de la aplicación "examples" de web2py. -The ``counter`` argument is used for line numbering. It can be set to any of three different values. It can be ``None`` for no line numbers, a numerical value specifying the start number, or a string. If the counter is set to a string, it is interpreted as a prompt, and there are no line numbers. +El argumento ``counter`` se usa para numeración de líneas. Se puede establecer según tres opciones. Puede ser ``None`` para omitir números de línea, un valor numérico indicando el número inicial, o una cadena. Si el contador se especifica con una cadena, es interpretado como un símbolo (prompt), y no se crean números de línea. -The ``styles`` argument is a bit tricky. If you look at the generated HTML above, it contains a table with two columns, and each column has its own style declared inline using CSS. The ``styles`` attributes allows you to override those two CSS styles. For example: +El argumento ``styles`` es un poco complicado. Si observas el HTML generado arriba, notarás que contiene una tabla con dos columnas, y cada columna tiene su propio estilo declarado por línea utilizando CSS. Los atributos ``style`` te dan la posibilidad de sobreescribir esos estilos CSS. Por ejemplo: `` {{=CODE(...,styles={'CODE':'margin: 0;padding: 5px;border: none;'})}} ``:code -The ``styles`` attribute must be a dictionary, and it allows two possible keys: ``CODE`` for the style of the actual code, and ``LINENUMBERS`` for the style of the left column, which contains the line numbers. Mind that these styles completely replace the default styles and are not simply added to them. +El atributo ``styles`` debe ser un diccionario, y permite dos posibles valores: ``CODE`` para el estilo del código en si, y ``LINENUMBERS`` para el estilo de la columna izquierda, que contiene los números de línea. Ten en cuenta que estos estilos no se agregan a los estilos existentes, sino que los sustituyen. ##### ``COL`` ``COL``:inxx @@ -543,47 +595,51 @@ The ``styles`` attribute must be a dictionary, and it allows two possible keys: ``:code ##### ``DIV`` -All helpers apart from ``XML`` are derived from ``DIV`` and inherit its basic methods. +Todos los ayudantes a excepción de ``XML`` derivan de ``DIV`` y heredan sus métodos básicos. ``DIV``:inxx `` ->>> print DIV('', XML('world'), _class='test', _id=0) -
<hello>world
+>>> print DIV('', XML('mundo'), _class='prueba', _id=0) +
<hola>mundo
``:code ##### ``EM`` -Emphasizes its content. +Enfatiza su contenido ``EM``:inxx `` ->>> print EM('', XML('world'), _class='test', _id=0) -<hello>world +>>> print EM('', XML('mundo'), _class='prueba', _id=0) +<hola>mundo ``:code ##### ``FIELDSET`` ``FIELDSET``:inxx -This is used to create an input field together with its label. +Esto se utiliza para crear un campo de carga de datos (input) junto con su etiqueta (label). + `` ->>> print FIELDSET('Height:', INPUT(_name='height'), _class='test') -
Height:
+>>> print FIELDSET('Altura:', INPUT(_name='altura'), _class='prueba') +
Alto:
``:code ##### ``FORM`` ``FORM``:inxx -This is one of the most important helpers. In its simple form, it just makes a ``
...
`` tag, but because helpers are objects and have knowledge of what they contain, they can process submitted forms (for example, perform validation of the fields). This will be discussed in detail in Chapter 7. + +Este es uno de los ayudantes más importantes. Es un simple formulario, sencillamente crea una etiqueta ``
...
``, pero como los ayudantes son objetos y tienen control de su contenido, pueden procesar formularios enviados (por ejemplo, realizar validación de los campos). Esto se tratará en detalle en el capítulo 7. + `` >>> print FORM(INPUT(_type='submit'), _action='', _method='post')
``:code -The "enctype" is "multipart/form-data" by default. +El "enctype" es "multipart/form-data" por defecto. ``hidden``:inxx -The constructor of a ``FORM``, and of ``SQLFORM``, can also take a special argument called ``hidden``. When a dictionary is passed as ``hidden``, its items are translated into "hidden" INPUT fields. For example: +El constructor de un ``FORM``, y el de un ``SQLFORM``, puede además tomar un argumento llamado ``hidden``. Cuando un diccionario se pasa como ``hidden`` (oculto), sus item son traducidos como campos INPUT de tipo "hidden". Por ejemplo: + `` >>> print FORM(hidden=dict(a='b'))
@@ -593,55 +649,60 @@ The constructor of a ``FORM``, and of ``SQLFORM``, can also take a special argum ##### ``H1``, ``H2``, ``H3``, ``H4``, ``H5``, ``H6`` ``H1``:inxx -These helpers are for paragraph headings and subheadings: +Estos ayudantes son para los títulos de párrafos y encabezados menores: + `` ->>> print H1('', XML('world'), _class='test', _id=0) -

<hello>world

+>>> print H1('', XML('mundo'), _class='prueba', _id=0) +

<hola>mundo

``:code ##### ``HEAD`` -For tagging the HEAD of an HTML page. +Para crear la etiqueta HEAD de una página HTML. ``HEAD``:inxx `` ->>> print HEAD(TITLE('', XML('world'))) -<hello><b>world</b> +>>> print HEAD(TITLE('', XML('mundo'))) +<hola><b>mundo</b> ``:code ##### ``HTML`` ``HTML``:inxx ``XHTML``:inxx -This helper is a little different. In addition to making the ```` tags, -it prepends the tag with a doctype string``xhtml-w,xhtml-o,xhtml-school``:cite . +Este ayudante es un tanto diferente. Además de crear las etiquetas ````, +configura la etiqueta con una cadena doctype ``xhtml-w,xhtml-o,xhtml-school``:cite . + `` ->>> print HTML(BODY('', XML('world'))) +>>> print HTML(BODY('', XML('mundo'))) -<hello>world +<hola>mundo ``:code -The HTML helper also takes some additional optional arguments that have the following default: +El ayudante HTML también recibe algunos argumentos opcionales que tienen los siguientes valores por defecto: + `` HTML(..., lang='en', doctype='transitional') ``:code -where doctype can be 'strict', 'transitional', 'frameset', 'html5', or a full doctype string. +donde doctype puede ser 'strict', 'transitional', 'frameset', 'html5', o una cadena doctype completa. ##### ``XHTML`` ``XHTML``:inxx -XHTML is similar to HTML but it creates an XHTML doctype instead. +XHTML es similar a HTML pero en cambio crea un doctype XHTML. + `` XHTML(..., lang='en', doctype='transitional', xmlns='http://www.w3.org/1999/xhtml') ``:code -where doctype can be 'strict', 'transitional', 'frameset', or a full doctype string. +donde doctype puede ser 'strict', 'transitional', 'frameset', o una cadena doctype completa. ##### ``HR`` ``HR``:inxx -This helper creates a horizontal line in an HTML page +Este ayudante crea una línea horizontal en la página + `` >>> print HR()
@@ -650,51 +711,53 @@ This helper creates a horizontal line in an HTML page ##### ``I`` ``I``:inxx -This helper makes its contents italic. +Este ayudante hace que el contenido sea en letra inclinada (italic). + `` ->>> print I('', XML('world'), _class='test', _id=0) -<hello>world +>>> print I('', XML('mundo'), _class='prueba', _id=0) +<hola>mundo ``:code ##### ``INPUT`` ``INPUT``:inxx -Creates an ```` tag. An input tag may not contain other tags, and is closed by ``/>`` instead of ``>``. The input tag has an optional attribute ``_type`` that can be set to "text" (the default), "submit", "checkbox", or "radio". +Crea una etiqueta ````. Una etiqueta input puede no contener otras etiquetas y es cerrada por ``/>`` en lugar de ``>``. La etiqueta input tiene un atributo opcional ``_type`` que se puede establecer como "text" (por defecto), "submit", "checkbox" o "radio". + `` ->>> print INPUT(_name='test', _value='a') - +>>> print INPUT(_name='prueba', _value='a') + ``:code -It also takes an optional special argument called "value", distinct from "_value". The latter sets the default value for the input field; the former sets its current value. For an input of type "text", the former overrides the latter: +Además toma un argumento opcional especial llamado "value", distinto de "_value". El último establece el valor por defecto para el campo input; el primero establece su valor actual. Para un input de tipo "text", el primero sobreescribe al segundo: `` ->>> print INPUT(_name='test', _value='a', value='b') - +>>> print INPUT(_name='prueba', _value='a', value='b') + ``:code -For radio buttons, ``INPUT`` selectively sets the "checked" attribute: +Para los botones tipo radio, ``INPUT`` establece el valor "checked" según la selección: ``radio``:inxx `` >>> for v in ['a', 'b', 'c']: ->>> print INPUT(_type='radio', _name='test', _value=v, value='b'), v - a - b - c +>>> print INPUT(_type='radio', _name='prueba', _value=v, value='b'), v + a + b + c ``:code -and similarly for checkboxes: +y en forma similar para los checkbox: ``checkbox``:inxx `` ->>> print INPUT(_type='checkbox', _name='test', _value='a', value=True) - ->>> print INPUT(_type='checkbox', _name='test', _value='a', value=False) - +>>> print INPUT(_type='checkbox', _name='prueba', _value='a', value=True) + +>>> print INPUT(_type='checkbox', _name='prueba', _value='a', value=False) + ``:code ##### ``IFRAME`` -This helper includes another web page in the current page. The url of the other page is specified via the "_src" attribute. +Este ayudante incluye otra página web en la página web actual. El url de la otra página se especifica por el atributo "_src". ``IFRAME``:inxx `` @@ -705,155 +768,156 @@ This helper includes another web page in the current page. The url of the other ##### ``IMG`` ``IMG``:inxx -It can be used to embed images into HTML: +Se puede usar para embeber imágenes en HTML: `` ->>> IMG(_src='http://example.com/image.png',_alt='test') -rest +>>> IMG(_src='http://example.com/image.png',_alt='prueba') +prueba ``:code -Here is a combination of A, IMG, and URL helpers for including a static image with a link: +Aquí hay una combinación de los ayudantes A, IMG y URL para incluir una imagen estática con un link: `` ->>> A(IMG(_src=URL('static','logo.png'), _alt="My Logo"), +>>> A(IMG(_src=URL('static','logo.png'), _alt="Mi Logo"), _href=URL('default','index')) - My Logo + Mi Logo ``:code ##### ``LABEL`` -It is used to create a LABEL tag for an INPUT field. +Se usa para crear una etiqueta LABEL para un campo INPUT. ``LABEL``:inxx `` ->>> print LABEL('', XML('world'), _class='test', _id=0) - +>>> print LABEL('', XML('mundo'), _class='prueba', _id=0) + ``:code ##### ``LEGEND`` -It is used to create a legend tag for a field in a form. +Se usa para crear una etiqueta legend para un campo form. ``LEGEND``:inxx `` ->>> print LEGEND('Name', _for='myfield') -Name +>>> print LEGEND('Name', _for='micampo') +Name ``:code ##### ``LI`` -It makes a list item and should be contained in a ``UL`` or ``OL`` tag. +Crea un ítem de lista y debería incluirse en una etiqueta ``UL`` o ``OL``. ``LI``:inxx `` ->>> print LI('', XML('world'), _class='test', _id=0) -
  • <hello>world
  • +>>> print LI('', XML('mundo'), _class='prueba', _id=0) +
  • <hola>mundo
  • ``:code ##### ``META`` -To be used for building ``META`` tags in the ``HTML`` head. For example: +Se utiliza para crear etiquetas ``META`` en el encabezado ``HTML``. Por ejemplo: ``META``:inxx `` ->>> print META(_name='security', _content='high') - +>>> print META(_name='seguridad', _content='alta') + ``:code ##### ``MARKMIN`` -Implements the markmin wiki syntax. It converts the input text into output html according to the markmin rules described in the example below: +Implementa la sintaxis de wiki markmin. Convierte el texto de entrada en salida html según las reglas de markmin descriptas en el ejemplo que sigue: ``MARKMIN``:inxx `` ->>> print MARKMIN("this is **bold** or ''italic'' and this [[a link http://web2py.com]]") -

    this is bold or italic and -this a link

    +>>> print MARKMIN("esto es en **negrita** o ''inclinada'' y este es [[un link http://web2py.com]]") +

    esto es en negrita o inclinada y +este es un link

    ``:code -The markmin syntax is described in this file that ships with web2py: +La sintaxis markmin se describe en este archivo incluido con web2py: + `` http://127.0.0.1:8000/examples/static/markmin.html ``:code -and some examples are shown in chapter 12 in the context of plugin_wiki, which uses MARKMIN extensively. - -You can use markmin to generate HTML, LaTeX and PDF documents: +Puedes usar markmin para generar documentos HTML, LaTex y PDF: `` -m = "Hello **world** [[link http://web2py.com]]" +m = "hola **mundo** [[link http://web2py.com]]" from gluon.contrib.markmin.markmin2html import markmin2html print markmin2html(m) from gluon.contrib.markmin.markmin2latex import markmin2latex print markmin2latex(m) from gluon.contrib.markmin.markmin2pdf import markmin2pdf -print markmin2pdf(m) # requires pdflatex +print markmin2pdf(m) # requiere pdflatex `` -(the ``MARKMIN`` helper is a shortcut for ``markmin2html``) +(el ayudante ``MARKMIN`` es un atajo para ``markmin2html``) -Here is a basic syntax primer: +Esta es una pequeña introducción a la sintaxis: -------------------------------------------------- -**SOURCE** | **OUTPUT** -``# title`` | **title** -``## section`` | **section** -``### subsection`` | **subsection** -``**bold**`` | **bold** -``''italic''`` | ''italic'' -``!`!`verbatim`!`!`` | ``verbatim`` -``http://google.com`` | http://google.com -``http://...`` | ``http:...`` -``http://...png`` | ```` -``http://...mp3`` | ```` -``http://...mp4`` | ```` -``qr:http://...`` | ```` -``embed:http://...`` | ```` -``[[click me #myanchor]]`` | [[click me #myanchor]] -``$````$\int_a^b sin(x)dx$````$`` | $$\int_a^b sin(x)dx$$ +**CÓDIGO** | **SALIDA** +``# título`` | **título** +``## sección`` | **sección** +``### subsección`` | **subsección** +``**negrita**`` | **negrita** +``''inclinada''`` | ''inclinada'' +``!`!`verbatim`!`!`` | ``verbatim`` +``http://google.com`` | http://google.com +``http://...`` | ``http:...`` +``http://...png`` | ```` +``http://...mp3`` | ```` +``http://...mp4`` | ```` +``qr:http://...`` | ```` +``embed:http://...`` | ```` +``[[clic aquí #mianchor]]`` | [[clic aquí #mianchor]] +``$````$\int_a^b sin(x)dx$````$`` | $$\int_a^b sin(x)dx$$ --------------------------------------------------- -Simply including a link to an image, a videos or an audio files without markup result in the corresponding image, video or audio file beling included automatically (for audio and video it uses html