nexostudios

31ago/100

Zen Coding: A Speedy Way To Write HTML/CSS Code

En este post se presenta una nueva forma rápida de escribir código HTML utilizando la sintaxis de selector CSS-como - un conjunto de herramientas útiles para la alta velocidad de codificación HTML y CSS. Ha sido desarrollado por nuestro autor,  Serguéi Chikuyonok.

¿Cuánto tiempo le dedicas a escribir código HTML: todas esas etiquetas, atributos, citas, tirantes, etc Usted tiene más fácil si su editor de elección ha completado con el código, pero aún así hacer un montón de escribir.

Tuvimos el mismo problema en el mundo de JavaScript al que queríamos tener acceso a un elemento específico en una página Web. Teníamos que escribir mucho código, que se convirtió en realmente difícil el apoyo y la reutilización. Y entonces llegó frameworks de JavaScript, CSS, que introdujo los motores de selector. Ahora, puede utilizar expresiones CSS sencilla de acceder a los elementos DOM, que está muy bien.

Pero ¿qué pasa si usted podría utilizar no sólo para los selectores CSS estilo y elementos de acceso, pero para generar el código? Por ejemplo, ¿qué pasa si usted podría escribir esto ...

div # content> h1 + p

... Y ver esto como la salida?
ver el código fuente
de impresión?
1 <div id="content">
2 <h1> </ h1>
3 <p> / p>
4 </ div>

Hoy voy a presentar a Zen codificación de mercancías, un conjunto de herramientas para la alta velocidad de codificación HTML y CSS. Originalmente propuesto por Vadim Makeev (artículo en ruso) en abril de 2009, se ha desarrollado para su seguridad (es decir yo) de los últimos meses y finalmente ha llegado a un estado maduro. Codificación Zen consiste en dos componentes principales: un expansor abreviatura (abreviaturas son selectores CSS-similar) y Matcher-par de etiquetas HTML independiente del contexto. Vea este vídeo de demostración para ver lo que pueden hacer por usted.

Si desea omitir las instrucciones detalladas y una guía de uso, por favor, eche un vistazo a la demo y descargar el plugin de inmediato:

Demo

  • Demo (use Ctrl + , to expand an abbreviation, requires JavaScript)

Downloads (Full Support)

Downloads (Partial Support, “Expand Abbreviation” Only)

Now, let’s see how these tools work.

[Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #1 is Professional Web Design, 242 pages for just $9,90.]

Expand Abbreviation

The Expand Abbreviation function transforms CSS-like selectors into XHTML code. The term “abbreviation” might be a little confusing. Why not just call it a “CSS selector”? Well, the first reason is semantic: “selector” means to select something, but here we’re actually generating something, writing a shorter representation of longer code. Secondly, it supports only a small subset of real CSS selector syntax, in addition to introducing some new operators.

Here is a list of supported properties and operators:

  • E
    Element name (div, p);
  • E#id
    Element with identifier (div#content, p#intro, span#error);
  • E.class
    Element with classes (div.header, p.error.critial). You can combine classes and IDs, too: div#content.column.width;
  • E>N
    Child element (div>p, div#footer>p>span);
  • E+N
    Sibling element (h1+p, div#header+div#content+div#footer);
  • E*N
    Element multiplication (ul#nav>li*5>a);
  • E$*N
    Item numbering (ul#nav>li.item-$*5);

As you can see, you already know how to use Zen Coding: just write a simple CSS-like selector (oh, “abbreviation”—sorry), like so…

1 div#header>img.logo+ul#nav>li*4>a

…and then call the Expand Abbreviation action.

There are two custom operators: element multiplication and item numbering. If you want to generate, for example, five <li> elements, you would simply write li*5. It would repeat all descendant elements as well. If you wanted four <li> elements, with an <a> in each, you would simply write li*4>a, which would generate the following output:

1 <li><a href=""></a></li>
2 <li><a href=""></a></li>
3 <li><a href=""></a></li>
4 <li><a href=""></a></li>

The last one–item numbering is used when you want to mark a repeated element with its index. Suppose you want to generate three <div> elements with item1, item2 and item3 classes. You would write this abbreviation, div.item$*3:

1 <div class="item1"></div>
2 <div class="item2"></div>
3 <div class="item3"></div>

Just add a dollar sign wherever in the class or ID property that you want the index to appear, and as many an you want. So, this…

1 div#i$-test.class$$$*5

would be transformed into:

1 <div id="i1-test" class="class111"></div>
2 <div id="i2-test" class="class222"></div>
3 <div id="i3-test" class="class333"></div>
4 <div id="i4-test" class="class444"></div>
5 <div id="i5-test" class="class555"></div>

You’ll see that when you write the a abbreviation, the output is <a href=""></a>. Or, if you write img, the output is <img src="" alt="" />.

How does Zen Coding know when it should add default attributes to the generated tag or skip the closing tag? A special file, called zen_settings.js describes the outputted elements. It’s a simple JSON file that describes the abbreviations for each language (yes, you can define abbreviations for different syntaxes, such as HTML, XSL, CSS, etc.). The common language abbreviations definition looks like this:

01 'html': {
02 'snippets': {
03 'cc:ie6': '<!--[if lte IE 6]>\n\t${child}|\n<![endif]-->',
04 ...
05 },
06
07 'abbreviations': {
08 'a': '<a href=""></a>',
09 'img': '<img src="" alt="" />',
10 ...
11 }
12 }

Element Types

Zen Coding has two major element types: “snippets” and “abbreviations.” Snippets are arbitrary code fragments, while abbreviations are tag definitions. With snippets, you can write anything you want, and it will be outputted as is; but you have to manually format it (using \n and \t for new lines and indentation) and put the ${child} variable where you want to output the child elements, like so: cc:ie6>style. If you don’t include the ${child} variable, the child elements are outputted after the snippet.

With abbreviations, you have to write tag definitions, and the syntax is very important. Normally, you have to write a simple tag with all default attributes in it, like so: <a href=""></a>. When Zen Coding is loaded, it parses a tag definition into a special object that describes the tag’s name, attributes (including their order) and whether the tag is empty. So, if you wrote <img src="" alt="" />, you would be telling Zen Coding that this tag must be empty, and the “Expand Abbreviation” action would apply special rules to it before outputting.

For both snippets and abbreviations, you can ad a pipe character (|), which tells Zen Coding where it should place the cursor when the abbreviation is expanded. By default, Zen Coding puts the cursor between quotes in empty attributes and between the opening and closing tag.

Example

So, here’s what happens when you write an abbreviation and call the “Expand Abbreviation” action. First, it splits a whole abbreviation into separate elements: so, div>a would be split into div and a elements, with their relationship preserved. Then, for each element, the parser looks for a definition inside the snippets and then inside the abbreviations. If it doesn’t find one, it uses the element’s name as the name for the new tag, applying ID and class attributes to it. For example, if you write mytag#example, and the parser cannot find the mytag definition among the snippets or abbreviation, it will output <mytag id="example"><mytag>.

We have made a lot of default CSS and HTML abbreviations and snippets. You may find that learning them increases your productivity with Zen Coding.

HTML Pair Matcher

Another very common task for the HTML coder is to find the tag pair of an element (also known as “balancing”). Let’s say you want to select the entire <div id="content"> tag and move it elsewhere or just delete it. Or perhaps you’re looking at a closing tag and want to known which opening tag it belongs to.

Unfortunately, many modern development tools lack support for this feature. So, I decided to write my own tag matcher as part of Zen Coding. It is still in beta and has some issues, but it works quite well and is fast. Instead of scanning the full document (as regular HTML pair matchers do), it finds the relevant tag from the cursor’s current position. This makes it very fast and context-independent: it works even with this JavaScript code snippet:

1 var table = '<table>';
2 for (var i = 0; i < 3; i++) {
3 table += '<tr>';
4 for (var j = 0; j < 5; j++) {
5 table += '<td>' + j + '</td>';
6 }
7 table += '</tr>';
8 }
9 table += '</table>';

Wrapping With Abbreviation

This is a really cool feature that combines the power of the abbreviation expander with the pair tag matcher. How many times have you found that you have to add a wrapping element to fix a browser bug? Or perhaps you have had to add decoration, such as a background image or border, to a block’s content? You have to write the opening tag, temporarily break your code, find the appropriate spot and then close the tag. Here’s where “Wrap with Abbreviation” helps.

This function is pretty simple: it asks you to enter the abbreviation, then it performs the regular “Expand Abbreviation” action and puts your desired text inside the last element of your abbreviation. If you haven’t selected any text, it fires up the pair matcher and use the result. It also makes sense of where your cursor is: inside the tag’s content or within the opening and closing tag. Depending on where it is, it wraps the tag’s content or the tag itself.

Abbreviation wrapping introduces a special abbreviation syntax for wrapping individual lines. Simply skip the number after the multiplication operator, like so: ul#nav>li*>a. When Zen Coding finds an element with an undefined multiplication number, it uses it as a repeating element: it is outputted as many times as there are lines in your selection, putting the content of each line inside the deepest child of the repeating element.

If you’ll wrap this abbreviation div#header>ul#navigation>li.item$*>a>span around this text…

About Us
Products
News
Blog
Contact Up

You’ll get the following result:

1 <div id="header">
2 <ul id="navigation">
3 <li class="item1"><a href=""><span>About Us</span></a></li>
4 <li class="item2"><a href=""><span>Products</span></a></li>
5 <li class="item3"><a href=""><span>News</span></a></li>
6 <li class="item4"><a href=""><span>Blog</span></a></li>
7 <li class="item5"><a href=""><span>Contact Up</span></a></li>
8 </ul>
9 </div>

You can see that Zen Coding is quite a powerful text-processing tool.

Key Bindings

  • Ctrl+,
    Expand Abbreviation
  • Ctrl+M
    Match Pair
  • Ctrl+H
    Wrap with Abbreviation
  • Shift+Ctrl+M
    Merge Lines
  • Ctrl+Shift+?
    Previous Edit Point
  • Ctrl+Shift+?
    Next Edit Point
  • Ctrl+Shift+?
    Go to Matching Pair

Online Demo

You’ve learned a lot about how Zen Coding works and how it can make your coding easier. Why not try it yourself now, right here? Because Zen Coding is written in pure JavaScript and ported to Python, it can even work inside the browser, which makes it a prime candidate for including in a CMS.

  • Demo (use Ctrl + , to expand an abbreviation, requires JavaScript)

Supported Editors

Zen Coding doesn’t depend on any particular editor. It’s a stand-alone component that works with text only: it takes text, does something to it and then returns new text (or indexes, for tag matching). Zen Coding is written in JavaScript and Python, so it can run on virtually any platform out of the box. On Windows, you can run the JavaScript version of Windows Scripting Host. And modern Macs and Linux distributions are bundled with Python.

To make your editor support Zen Coding, you need to write a special plug-in that can transfer data between your editor and Zen Coding. The problem is that an editor may not have full Zen Coding support because of its plug-in system. For example, TextMate easily supports the “Expand Abbreviation” action by replacing the current line with the script output, but it can’t handle pair-tag matching because there’s no standard way to ask TextMate to select something.

Full Support

Partial Support (“Expand Abbreviation” Only)

Aptana is my primary development environment, and it uses a JavaScript version of Zen Coding. It also contains many more tools that I use for routine work. Every new version of Zen Coding will be available for Aptana first, then ported to Python and made available to other editors.

The Coda and Espresso plug-ins are powered by the excellent Text Editor Actions (TEA) platform, developed by Ian Beck. The original source code is available at GitHub, but I made my own fork to integrate Zen Coding’s features.

Conclusion

Many people who have tried Zen Coding have said that it has changed their way of creating Web pages. There’s still a lot of work to do, many editors to support and much documentation to write. Feel free to browse the existing documentation and source code to find answers to your questions. Hope you enjoy Zen Coding!

Archivado en: HTML Deja un comentario
Comentarios (0) Trackbacks (0)

Aún no hay comentarios.


Leave a comment

(required)

Aún no hay trackbacks.