📜 ⬆️ ⬇️

Introduction to JadePHP

At the suggestion of the author of interesting and useful for web developer # 17 , I offer my translation of the article Introduction to JadePHP .

There are dozens of template engines. Among the most famous are Smarty , Twig (used in the next version of Drupal), Blade (used by default in Laravel) and, of course, vanilla PHP. If we don’t speak specifically about PHP, then for eRuby / ERB and Haml for Ruby / Ruby on Rails and Javascript there are a number of popular options, such as Mustache , Handlebars , Hogan and EJS . In some, the differences in syntax are minor, in others they are more pronounced.

The Jade template engine, which is significantly different from the others, is usually associated with JavaScript applications, for example, it is supported in Express for Node.js. In this article, I'll talk about Jade or, more specifically, about Jade made for PHP - JadePHP .

Haml and jade


It would be wrong to talk about Jade without mentioning Haml, which was an inspirational idea for Jade. And in fact, there are several libraries to support Haml in PHP. Jade adheres to the same philosophy as HAML, that is, creating “beautiful” templates and what the authors call haiku templating. Whatever that means, Haml and Jade have some of the same qualities that fundamentally distinguish them from most other template engines.
')

What is the difference?


Most template engines assume the writing of the final markup with the “implementation” of placeholders and the main logic in it. Jade, on the other hand, has not only place holders and logic, but also a way to write abbreviated XML for similar elements. In general, this means HTML, although you can use it for RSS and XML itself.

In essence, if you want, you can use Jade as shorthand for HTML without its “traditional” template-specific capabilities.

How to use the repository


Unfortunately, at the moment the code is not available through Composer , although it is not difficult to pack it, if someone has another hour. But you can start it by cloning the repository and turning on autoload.php.dist (the Github repository includes the UniversalClassLoader from Symphony).

Below, an adapted example from the README project. It is assumed that the repository was placed in the jade directory.

 use Everzet\Jade\Dumper\PHPDumper, Everzet\Jade\Visitor\AutotagsVisitor, Everzet\Jade\Filter\JavaScriptFilter, Everzet\Jade\Filter\CDATAFilter, Everzet\Jade\Filter\PHPFilter, Everzet\Jade\Filter\CSSFilter, Everzet\Jade\Parser, Everzet\Jade\Lexer\Lexer, Everzet\Jade\Jade; $dumper = new PHPDumper(); $dumper->registerVisitor('tag', new AutotagsVisitor()); $dumper->registerFilter('javascript', new JavaScriptFilter()); $dumper->registerFilter('cdata', new CDATAFilter()); $dumper->registerFilter('php', new PHPFilter()); $dumper->registerFilter('style', new CSSFilter()); // Initialize parser & Jade $parser = new Parser(new Lexer()); $jade = new Jade($parser, $dumper); $template = __DIR__ . '/template.jade'; // Parse a template (both string & file containers) echo $jade->render($template); 

This code will compile the tempalte.jade file and show its contents.

Where it can be applied depends on your workflow, for example, whether you use a framework, etc. For example, you could use a service like Watchman , Guard or Resource Watcher to monitor the file system and changes in your Jade templates, and compile them at a specific time during the development process.

Simple example


Consider a simple example that displays a full HTML page with two variables, so far without logic.
 !!! 5 html(lang="en-us") meta(charset="utf-8") meta(http-equiv="X-UA-Compatible", content="IE=Edge;chrome=1") title(dir="ltr")= pageTitle meta(name="viewport", content="width=device-width, initial-scale=1.0") link(rel="stylesheet", media="screen", href="/css/styles.css") body header h1 My Jade Application div#content div.inner =$bodyContent script(data-main="js/main.js", src="js/libs/require.js") 

Important: you must use two spaces for indentation. At the moment this is the only method understandable Jade PHP. Otherwise, errors will occur or it will be incorrect markup.

Immediately it becomes obvious, Jade is quite different from the usual HTML. First, it does not have angle brackets <> and closing tags. And also there are no curly brackets, double curly brackets or other common methods for designating variables in templates. (However, you can use the syntax with double curly braces. But this is not part of Jade).

Jade looks like a very compressed method for generating markup. Look at the final HTML:
 <!DOCTYPE html> <html lang="en-us"> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1" /> <title dir="ltr"><?php echo pageTitle ?></title> <meta name="viewport" content="width=device-width" initial-scale="1.0" /> <link rel="stylesheet" media="screen" href="/css/styles.css" /> <body> <header> <h1>My Jade Application</h1> </header> <div id="content"> <div class="inner"> <?php echo $bodyContent ?> </div> </div> <script data-main="js/main.js" src="js/libs/require.js"></script> </body> </html> 


Go through all the key lines in the Jade template in order to understand how HTML shortcuts work.

!!! 5 !!! 5 is an abbreviation for HTML5 doctype. This is the only place where you will see a triple exclamation point in syntax. You can also use !!! xml !!! xml to get <?xml version="1.0" encoding="utf-8" ?> . For transitional , you can use !!! transitional !!! transitional to get <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> . By default !!! default !!! default will give <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Note: in the latest version of Jade, spiced with javascript ad !!! 5 !!! 5 been changed to doctype html . Perhaps JadePHP will follow this example, although probably not, judging by the lack of activity on Github.

HTML tag is indicated by one of its name, without the need to close it. For example:
 body header 

... if you would stop at this, you would have the following result:
 <body> <header></header> </body> 

Notice how the document structure is indented.

You can put the contents of the tag after its name with spaces:

 h1 My Jade Application 

... becomes
 <h1>My Jade Application</h1> 

If you want to break large blocks with content into lines, use the pipe | character:
 p | Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. | Aenean eu leo quam. | Pellentesque ornare sem lacinia quam venenatis vestibulum. 

This will compile to:
 <p>Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.</p> 

You can use a format similar to CSS selectors to add id and class attributes to HTML elements:
 div#content div.inner 

… leads to:
  <div id="content"> <div class="inner"> 

Other attributes like src, href, lang, media, etc. can be specified using parentheses:
 html(lang="en-us") === <html lang="en-us"> link(rel="stylesheet", media="screen", href="/css/styles.css") === <link rel="stylesheet" media="screen" href="/css/styles.css" /> 

The equal sign is used for variable substitution. As you can see above, when you compile a jade template, it converts:
 = $pageTitle 

in the following:
 <?php echo $pageTitle ?> 


Add some logic


You can use dashes for conditional logic. Here is a specific example:
 header h1= $pageTitle - if ($loggedIn): p.greeting Welcome back! - else: a(href="/login") Please login - endif; 

If you compile this template, the result is the following:
 <header> <h1><?php echo $pageTitle ?></h1> <?php if ($loggedIn) ?> <p class="greeting">Welcome back!</p> <?php else ?> <a href="/login">Please login</a> <?php endif ?> </header> 

For loops, the code is very similar:
 ul - foreach ($items as $item): li= $item 


Filters


JadePHP has the ability to use filters to process blocks of text in various ways. For example:
 :php | $value = 10; | $computed_value += 100; | print $computed_value; 

... will be converted to:
 <?php $value = 10; $computed_value += 100; print $computed_value; ?> 

Probably more useful filters will be for javascript and css. For example:
 :style | body { | background: yellow; | } 

... will be converted to:
 <style type="text/css"> body { background: yellow; } 

These filters are set as follows (see the code example above for an understanding of the context of these ads):
 $dumper->registerFilter('javascript', new JavaScriptFilter()); $dumper->registerFilter('php', new PHPFilter()); $dumper->registerFilter('style', new CSSFilter()); 

The first argument is the text that you mark up in your template with a colon added. For the example above, you can use :javascript :php and :style respectively.

If you enable Everzet\Jade\Filter\FilterInterface , then you can even define your own filters.

Why use Jade?


Disputes about which template engines to use are ultimately pretty useless. You can do tests in order to determine which templating engines are better in performance under various conditions, and which ones are more suitable in certain environments, for example, on a client or server. But in the end, the choice often depends on what is more comfortable for you. I have no intention of adding fuel to the fire, as well as participating in debates about the best programming language.

The Jade pruning method is not for everyone. Some people will argue that it is easier to read, while others will passionately disagree. But if you think that this is a worthy method, then this is already a good reason to choose it.

Another reason you can decide to use Jade (by the way about the number of templating engines) is the alternation between technologies. If you often switch between, say, Node.js and PHP, then there is some logic to maintain consistency. Why study one tool and then use something completely different if it is available for many languages?

Summary


In this article, I looked at JadePHP, a ported Jade templating engine, originally focused on JavaScript. I gave you a few tips on how to use it, and ideas on why you might need it. Will you try it, or does it seem unreasonably compressed to you? Write what you think about him in the comments.

Source: https://habr.com/ru/post/224391/


All Articles