ビュー内の関数

□未翻訳

□翻訳中

■翻訳完了(細田謙二)

■レビュー(Omi Chiba)

ビュー内の関数

次の"layout.html"を考えます:

Consider this "layout.html":

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

<html>

<body>

{{include}} <!-- must come before the two blocks below -->

<div class="sidebar">

{{if 'mysidebar' in globals():}}{{mysidebar()}}{{else:}}

my default sidebar

{{pass}}

</div>

</body>

</html>

そして、次の拡張ビューも考えます

and this extending view

1.

2.

3.

4.

5.

{{def mysidebar():}}

my new sidebar!!!

{{return}}

{{extend 'layout.html'}}

Hello World!!!

ここで、関数が{{extend...}}文の前に定義されていることに注意してください。また、関数が、拡張元のビューにおいて = プレフィックスが付かずに組み込まれていることに注意してください。

Notice the function defined before the {{extend...}} statement. Also notice the function is included in the extended view without the = prefix.

このコー​​ドは次のような出力を生成します:

The code generates the following output:

1.

2.

3.

4.

5.

6.

7.

8.

<html>

<body>

Hello World!!!

<div class="sidebar">

my new sidebar!!!

</div>

</body>

</html>

この関数が(Pythonコードを含みますが)HTMLの中で定義されることで、response.write がその内容を書くために使用されていることに注意してください(関数はその内容を返しません)。このような理由で、レイアウトでは、{{=mysidebar()}}ではなく{{mysidebar()}}を用いてビュー関数を読んでいます。このような方法で定義された関数は、引数を取ることができます。

Notice that the functions are defined in HTML (although they can also contain Python code) so that response.write is used to write their content (the functions do not return the content). This is why the layout calls the view function using {{mysidebar()}} rather than{{=mysidebar()}}. Functions defined in this way can take arguments.