JadePHP简介

tech2023-07-12  85

There are dozens of templating engines out there, with options such as Smarty, Twig (used in the upcoming version of Drupal) and Blade (the default for Laravel) among the best known – as well as vanilla PHP, of course. Stepping away from PHP specifically, eRuby / ERB and Haml for Ruby / Ruby on Rails, and Javascript has scores of popular choices including Mustache, Handlebars, Hogan and EJS. Some have subtly different syntax, some more markedly so.

那里有数十种模板引擎,其中包括最知名的选项包括Smarty , Twig (在即将发布的Drupal版本中使用)和Blade(默认为Laravel)以及香草PHP。 专门脱离PHP的是eRuby / ERB和Haml for Ruby / Ruby on Rails,而Javascript则有数 十种受欢迎的选择,包括Mustache , Handlebars , Hogan和EJS 。 有些语法略有不同,有些则明显不同。

One which differs quite significantly from most is Jade, an engine usually associated with Javascript applications – it’s supported out-of-the-box by Express for Node.js, for example. It’s Jade I’m going to look at in this article; or more specifically the PHP port JadePHP.

与大多数服务器有很大不同的是Jade ,该引擎通常与Javascript应用程序相关联-例如,Express for Node.js便已支持它。 我将在本文中讨论的是玉。 或更具体地说,是PHP端口JadePHP 。

哈姆和玉 (Haml and Jade)

It would be remiss to talk about Jade without mentioning Haml, from which Jade takes its inspiration – and indeed there are several libraries for using Haml with PHP. Jade shares its overall philosophy, which is to make templating “beautiful” and use what the authors describe as templating “haiku”. Whatever that actually means, there’s no denying Haml and Jade do share some characteristics which make them fundamentally different to most templating languages.

谈论Jade而不提及Haml会被忽略,Jade的灵感来自于Haml –实际上, 有 几个 库可以将Haml与PHP结合使用。 Jade拥有其总体理念,即使模板“美丽”并使用作者描述的模板“ haiku”。 无论实际上意味着什么,无可否认,Haml和Jade确实具有某些特征,这使其与大多数模板语言根本不同。

有什么不同? (What’s the Difference?)

Most templating engines involve writing the target markup and “injecting” it with placeholders and / or basic logic – a superset, in a sense. Jade still has placeholders and logic, but also provides a shorthand for writing XML-like elements. Generally that means HTML, although you can also use it for things like RSS as well as XML itself.

大多数模板引擎都涉及编写目标标记,并用占位符和/或基本逻辑(某种意义上说是超集)“注入”目标标记。 Jade仍然具有占位符和逻辑,但是也提供了编写类似XML的元素的捷径。 通常,这意味着HTML,尽管您也可以将其用于RSS和XML本身。

In fact if you wanted to, you could just use Jade as a shorthand for HTML without taking advantage of its more “traditional” templating features.

实际上,如果您愿意,可以仅将Jade用作HTML的简写,而无需利用其更多的“传统”模板功能。

如何使用储存库 (How to use the Repository)

Rather frustratingly, the code is not currently available via Composer – although it should be a simple enough task to package it up, if anyone has an hour or two. You can get it to to work, however, by cloning the repository and include‘ing or require‘ing the included autoload.php.dist (the Github repository includes Symfony’s UniversalClassLoader).

令人沮丧的是,该代码目前无法通过Composer获得 -尽管如果有人有一个或两个小时的时间,将它打结语应该是一个简单的任务。 你可以得到它的工作,但是,通过克隆库和include “荷兰国际集团或require ”荷兰国际集团所包含的autoload.php.dist (GitHub的资源库包括的Symfony的UniversalClassLoader )。

Here’s an example, adapted from the one in the project’s README, which assumes that the repository has been downloaded into a directory called jade:

这是一个示例,该示例改编自该项目的README中的示例,并假定该存储库已下载到名为jade的目录中:

require('./jade/autoload.php.dist'); 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 will compile the file template.jade and echo its contents.

这将编译文件template.jade并echo其内容。

Where you actually use this depends on your workflow, whether you’re using a framework, and so on. You could, perhaps, use a service such as Watchman, Guard or Resource Watcher to watch the filesystem for changes to your Jade templates, and compile them at the appropriate time during the development process.

当你实际使用这取决于你的工作流程,无论您使用的是框架,等等。 也许您可以使用Watchman , Guard或Resource Watcher之类的服务来监视文件系统中Jade模板的更改,并在开发过程中的适当时间对其进行编译。

一个简单的例子 (A simple example)

Let’s look at a simple example, which shows a complete – if basic – HTML page, with only two variables and no logic (yet!)

让我们看一个简单的示例,该示例显示了完整HTML页面(如果是基本的),只有两个变量且没有逻辑(还!)。

!!! 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’ll need to use two spaces to indent. This is the only method currently understood by Jade PHP, and using something different will cause errors or invalid markup.

重要提示 :您需要使用两个空格来缩进。 这是Jade PHP当前了解的唯一方法,使用其他方法会导致错误或无效的标记。

Straight away, it will be apparent that Jade looks rather different to the HTML you’re accustomed to. No angled brackets and no closing tags, for starters. Nor are there curly brackets, double curly brackets, or any of the common approaches to marking up variables to be injected into the template. (That said, you can use the double curly bracket syntax, but it’s not a part of Jade, per se.)

显而易见,Jade看起来与您习惯HTML完全不同。 对于初学者,没有尖括号和没有结束标记。 也没有大括号,双大括号或标记要注入模板的变量的任何常用方法。 (也就是说,您可以使用双花​​括号语法,但是它本身并不是Jade的一部分。)

What it does show is a very concise method of generating markup. Let’s look at the resulting HTML:

它所显示的是一种非常简洁的生成标记的方法。 让我们看一下结果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>

Let’s go through the key lines in the Jade template, to get an idea of how the shorthand for HTML works.

让我们浏览一下Jade模板中的关键行,以了解HTML的简写方式。

!!! 5 is shorthand for the HTML5 doctype. It’s the only place you’ll see that triple exclamation mark syntax. You can also use !!! xml to get <?xml version="1.0" encoding="utf-8" ?>, for transitional you can use !!! transitional to get <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> or the default !!! default gives you <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">.

!!! 5 !!! 5是HTML5文档类型的简写。 这是您唯一看到三重感叹号语法的地方。 您也可以使用!!! xml !!! xml以获得<?xml version="1.0" encoding="utf-8" ?> ,对于过渡,您可以使用!!! transitional !!! transitional获取<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">或默认!!! default !!! default为<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 。

NOTE; in the latest Javascript-flavoured version of Jade, the !!! 5 declaration has been replaced with doctype html; it’s possible – though perhaps unlikely, looking at the Github repo’s lack of activity – that JadePHP will follow suit.

注意; 在最新的Javascript风格的Jade中, !!! 5 !!! 5声明已替换为doctype html ; 考虑到Github存储库缺乏活动性,JadePHP可能会效仿(尽管可能不太可能)。

An HTML tag is specified by its name alone, with no need to close it; for example:

HTML标记仅由其名称指定,而无需将其关闭; 例如:

body header

…would, if you stopped there, result in:

…如果您在此停留,将会导致:

<body> <header></header> </body>

Note how the structure of the document is represented using indentation.

请注意如何使用缩进表示文档的结构。

You can put a tag’s content after its name, with a space between them:

您可以将标签的内容放在其名称之后,并在其之间留一个空格:

h1 My Jade Application

…becomes:

…成为:

<h1>My Jade Application</h1>

If you want to split large blocks of content into multiple 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 compiles 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 IDs and classes to HTML elements:

您可以使用类似于CSS选择器的格式向HTML元素添加ID和类:

div#content div.inner

…results in:

…结果是:

<div id="content"> <div class="inner">

Other attributes such as src, href, lang, media etc can be specified using parenthesis:

可以使用括号指定其他属性,例如src , href , lang , media等。

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" />

An equals sign is used for variable substitution. As you can see above, when you compile a Jade template it converts something like this:

等号用于变​​量替换。 如上所示,当编译Jade模板时,它将转换为以下内容:

= $pageTitle

…into the following:

…以下:

<?php echo $pageTitle ?>

添加一些逻辑 (Adding some Logic)

You can use a dash to inject basic conditional logic. Here’s a concrete example:

您可以使用破折号插入基本条件逻辑。 这是一个具体的例子:

header h1= $pageTitle - if ($loggedIn): p.greeting Welcome back! - else: a(href="/login") Please login - endif;

When you compile the template, this will result in 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>

Iteration follows very similar lines:

迭代遵循非常相似的代码:

ul - foreach ($items as $item): li= $item

筛选器 (Filters)

You can use filters to take a block of text and process it in some way, for example:

您可以使用过滤器来获取文本块并以某种方式对其进行处理,例如:

:php | $value = 10; | $computed_value += 100; | print $computed_value;

…will evaluate to:

…将评估为:

<?php $value = 10; $computed_value += 100; print $computed_value; ?>

Perhaps more useful are the javascript and CSS filters, for example:

可能更有用的是javascript和CSS过滤器,例如:

:style | body { | background: yellow; | }

…will evaluate to:

…将评估为:

<style type="text/css"> body { background: yellow; }

You set up these filters as follows (see the example code above for the context of these declarations):

您可以按照以下步骤设置这些过滤器(有关这些声明的上下文,请参见上面的示例代码):

$dumper->registerFilter('javascript', new JavaScriptFilter()); $dumper->registerFilter('php', new PHPFilter()); $dumper->registerFilter('style', new CSSFilter());

The first argument corresponds to the text you use to “mark up” the text in your templates, which is prefixed with a colon; so in the example above you could use :javascript, :php and :style respectively.

第一个参数与您用来“标记”模板中文本的文本相对应,并以冒号作为前缀。 因此,在上面的示例中,您可以分别使用:javascript , :php和:style 。

By implementing Everzet\Jade\Filter\FilterInterface, you can even define your own filters.

通过实现Everzet\Jade\Filter\FilterInterface ,您甚至可以定义自己的过滤器。

为什么要使用翡翠? (Why use Jade?)

Arguments about which templating language to use are ultimately pretty futile. Whilst you can come up with certain benchmarks about which perform better than others in certain circumstances, which ones are specifically designed for certain environments – like client vs server-side, at the end of the day the choice is often a very personal one which comes down to what you feel comfortable scripting in. I have no intention of trying to fan those flames, any more than I wish to get involved in arguments over which is “the best” programming language.

关于使用哪种模板语言的争论最终都是徒劳的。 尽管您可以提出某些基准,以确保在某些情况下性能比其他基准更好,但是这些基准是专门为特定环境(例如客户端与服务器端)设计的,最终,选择往往是非常个人化的选择直到您对脚本编写感到满意为止。我无意试图煽动这些火焰,无非是希望参与有关“最佳”编程语言的争论。

Jade’s shorthand approach won’t be for everyone. There are some who will argue that it’s easier to read, and some who will vehemently disagree. If, however, it’s an approach that you see the merit in then that’s a compelling reason to choose it.

Jade的速记方法并不适合所有人。 有些人会认为它更容易阅读,而有些人会强烈不同意。 但是,如果您看到的是这种方法的优点,那就是选择它的迫切理由。

Another reason you might decide to use Jade – apropos of a number of templating options – is if you alternate between technologies. If you often switch between, say, Node.js and PHP development then there’s some logic in keeping things consistent. Why master one engine then use something else entirely, if it’s available for multiple languages?

您可能决定使用Jade的另一个原因-许多模板选项的选择-如果您在技术之间交替使用。 例如,如果您经常在Node.js和PHP开发之间进行切换,那么保持事物一致就有些逻辑。 如果可以支持多种语言,为什么要掌握一个引擎然后完全使用其他东西呢?

摘要 (Summary)

In this article I’ve looked at JadePHP, a port of the primarily Javascript-focussed templating engine, Jade. I’ve given you a few pointers on how to use it and some ideas about why you might want to use it. Are you going to give it a try, or does it seem unnecessarily terse to you? Do let me know what you think of it in the comments.

在本文中,我研究了JadePHP,它是主要关注Java脚本的模板引擎Jade的移植。 我为您提供了一些有关如何使用它的指导,以及一些有关您为什么要使用它的想法。 您是要尝试一下,还是觉得它不必要地过于简洁? 请在评论中告诉我您的想法。

翻译自: https://www.sitepoint.com/introduction-jadephp/

相关资源:jdk-8u281-windows-x64.exe
最新回复(0)