Differences between revisions 3 and 7 (spanning 4 versions)
Revision 3 as of 2009-02-24 14:12:47
Size: 644
Editor: 147
Comment:
Revision 7 as of 2009-02-24 14:30:30
Size: 1050
Editor: 147
Comment:
Deletions are marked like this. Additions are marked like this.
Line 13: Line 13:
Vytvoríme v adresári projektu {{{hello}}} podadresár s názvom napr. {{{templates}}}.
V podadresári {{{templates}}} vytvoríme šablónu hello.html:
 * Vytvoríme v adresári projektu {{{hello}}} podadresár s názvom napr. {{{templates}}}.
 * V podadresári {{{templates}}} vytvoríme šablónu hello.html (Nazval som ju tu z technických
dôvodov {{{hello.txt}}}.) {{attachment:hello.txt}}
 * Musíme djangu povedať, z ktorého adresára má načítavať templates. V {{{settings.py}}} pridáme do {{{TEMPLATE_DIRS}}} reťazec
{{{#!python
'/home/gejza/django/hello/templates'
}}}
 * Cesta musí byť absolútna!
 * {{{views.py}}} vyzerá takto: {{attachment:views.py}}
Line 16: Line 23:
{{{attachment:hello.txt}}}
Celý projekt máte tu: [[ attachment:hello_v3.tar.gz ]].

Hello, world verzia 3

Mať HTML kód vo vnútri view nie je dobrý nápad. HTML by malo byť iba v šablónach, aby sme mali jedno miesto, kde je HTML a nemuseli teda pri zmene HTML zasahovať do kódu.

Teraz ideme upraviť Hello, world verziu 2 tak, aby sme použili Template.

Keďže vytvárať Template zo stringu odporuje zásade v prvom odstavci, šablóny budú v súboroch.

  • Vytvoríme v adresári projektu hello podadresár s názvom napr. templates.

  • V podadresári templates vytvoríme šablónu hello.html (Nazval som ju tu z technických

   1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   3 <html>
   4 <style type="text/css">
   5 h1 {
   6 	color:red;
   7 	font-style:normal;
   8 }
   9 </style>
  10 <head>
  11 <title>
  12 Hello, world v3
  13 </title>
  14 </head>
  15 <body>
  16 <h1>
  17 Hello, {{ who }}.
  18 </h1>
  19 </body>
  20 </html>

dôvodov hello.txt.) hello.txt

  • Musíme djangu povedať, z ktorého adresára má načítavať templates. V settings.py pridáme do TEMPLATE_DIRS reťazec

   1 '/home/gejza/django/hello/templates'
  • Cesta musí byť absolútna!
       1 from django.http import HttpResponse
       2 from django.template import Context,loader
       3 
       4 def hello(request,who):
       5     t=loader.get_template('hello.html')
       6     c=Context({'who':who})
       7     html=t.render(c)
       8     return(HttpResponse(html))
    
  • views.py vyzerá takto: views.py

Celý projekt máte tu: hello_v3.tar.gz.

KMaDGWiki: ProgramovanieInternetovychAplikacii/HelloWorldV3 (last edited 2009-02-24 14:30:30 by 147)