web.py以及如何使用节块

时间:2016-11-28 19:17:27

标签: python web.py

我将web.py Templator用于我的项目并使用渲染('模板',base ="")我将基本布局与页面特定布局(简化)相结合

view.py
render = web.template.render('templates',base='layout')
return render.index()

共享布局文件

layout.html
$def with (content)
<html>
<head>
<title>$content.title</title>
</head>
<body>
$:content
</body>
</html>

页面特定模板

index.html
$def with (values)
$var title: Hello Kitty
<p>Hello $values, how are you doin?</p>

我正在寻找的解决方案是如何实现以下目标

login.html
$def with (values)
$var title: Enter credentials

<form>
<p><input type="text" name="user_name"></p>
<p><input type="password" name="user_pwd"></p>
<p><button type="submit">Open the gates</button></p>
</form>

$block_begin
<script>
// When the form is submitted, check the required fields and inform user
// if any data is missing or looks weird
</script>
$block_end

</body>
</html>

我的问题是,如何将脚本添加到login.html模板而不是index.html模板?我不想将所有JS逻辑添加到所有页面,我想添加这个$ block_begin / $ block_end,以便它出现在layout.html的底部,就像这样

layout.html
$def with (content)
<html>
<head>
<title>$content.title</title>
</head>
<body>
$:content

$block_begin
$block_end
</body>
</html>

$ block_begin / $ block_end只是我提出来更好地解释自己。

1 个答案:

答案 0 :(得分:0)

为了清楚起见,template -> defwith sections是一种语法,而不是一个例子。要使用模板,请查看http://webpy.org/docs/0.3/templetor以获取示例。

在较高级别,您可以创建类似于

的模板
=== templates/index.html ===
$def with(values)
$var title: Hello Kitty
<p>Hello $values, how are you doin?</p>

=== templates/layout.html ===
$def with(content)
<html>
 <head>
  <title>$content.title</title>
 </head>
 <body>
  $:content
 </body>
</html>

然后在你的python中你渲染模板,传入模板中指定的任何参数。 (&#34; values&#34;在此示例中。)命名模板(index.html)使用基础(layout.html)进行渲染,并且您已经发现了,content包含渲染的内部位(索引的结果)并插入到基本模板布局中。

您正在询问如何将一些脚本放入login.html,但不是在index.html&amp;这很简单:只需将javascript代码添加到login.html模板中即可。

=== login.html ===
$def with (values)
$var title: Enter credentials
<form>
...
</form>
<script>
  window.addEventListener('load', function () {
     // whatever javascript you want to execute on load.
     // If using jQuery, you'll have to use $$('form') or jQuery('form') rather
     // than $('form'), as dollar signs are special within the template.
  });
</script>

更聪明的东西?更充分地使用content。您在模板中使用$var定义的任何内容都会放入基本布局中的$content

如果您只想在呈现login.js页面时添加login.html,则可以简单地创建新的内容属性。在login.html:

$var extra_js: js/login.js

然后,在你的布局文件中有条件地加载底部的值(我们喜欢加载脚本的地方)。

=== templates/layout.html ===
...
<body>
  $:content
  $if content.get('extra_js', None):
      <script type="text/javascript" src="$content.extra_js"></script>
</body>
</html>

您可以使layout.html越来越强大,参数化元数据,脚本,CSS文件等。就像使用$content.title一样,让您的个人模板文件驱动整体布局的不同部分