2: Views

Views live directly in your .phlo files and transpile to PHP methods that return HTML. In this chapter you replace the hello route with the first real poll page: a question and a row of answer buttons. You learn the view block, the dot shorthand, variables, and the one rule that bites everyone once: a blank line closes the view.

2.1: 从 route 到 view

替换 poll.phlo 的内容:

prop question = '哪个栈获胜?'

route GET poll => $this->home

method home => view($this, 'Phlo Poll')

view:
<main#app.poll>
	<h1>$this->question</h1>
</main>

从上到下:prop questionpoll 类上的一个静态属性。该路由将 GET /poll 映射到 home 方法。home 调用 view($this, 'Phlo Poll'):第二个参数成为页面标题,传递 $this 作为主体渲染文件的 匿名视图,即以 view: 开头的无名块。

重新加载 http://localhost/poll。您会看到问题作为未样式化页面上的标题

2.2: 点简写

再次查看开标签:

<main#app.poll>

Phlo 直接在标签名称上扩展 #id.class

<main id="app" class="poll">

您可以堆叠类(<div.card.wide>),并且尾随斜杠会在源代码中自闭合标签:<div.spacer/> 变为 <div class="spacer"></div>。有一点需要注意:包含变量或斜杠的属性值需要引号,因此请写 <a href="/poll"><form action="/poll/vote/$id">

<main#app.poll> 更改为 <main#app.poll.wide>,重新加载并检查元素:类列表现在显示为 poll wide。再改回去。

2.3: 空行关闭视图

一个 view 块在 第一个空行 处结束。该空行之后的所有内容又是控制器代码。这是设计使然:它是将多个 views 放在一个文件中的方式。这也意味着你绝不能在 view 内部插入空行以进行视觉间隔;下面的 HTML 会泄漏到控制器代码中,构建会因 HTML outside a view 而停止。

view:
<h1>One view</h1>
<p>Still the same view, no blank lines.</p>

view footer:
<p>A second, named view. The blank line above ended the first one.</p>

试试看:在你的 view 中的 <h1></main> 之间放一个空行,重新加载并查看错误页面。它会命名确切的文件、行和关闭的 view。删除空行后,页面就会恢复。

2.4: Variables, expressions, and composition

Inside a view you have three levels of expression:

Extend poll.phlo with a static list of options and a second view:

prop question = 'Which stack wins?'
prop options = ['Phlo', 'Next.js', 'Laravel', 'Rails']

route GET poll => $this->home

method home => view($this, 'Phlo Poll')

view:
<main#app.poll>
	<h1>$this->question</h1>
	{{ $this->choices }}
</main>

view choices:
<section.card>
	<foreach $this->options AS $option>
		<button>$option</button>
	</foreach>
</section>

{{ $this->choices }} renders the named view choices inline; this is how you compose pages, because view(...) itself may only be called once per request. The <foreach> tag loops over the prop; note that it stands on its own line, never inline inside other HTML.

Reload http://localhost/poll: the question plus four plain buttons. Ugly, but alive. Next chapter: CSS.

我们使用必要的cookie来使该网站正常工作。在您的许可下,我们还使用分析工具来改善网站。