Attachment '01_templates.py'

Download

   1 # Prve interaktivne sedenie: Django Templates
   2 # 
   3 # Pouzitie: V existujucom django projekte
   4 # treba spustit "manage.py shell". 
   5 # To zabezpeci natiahnutie patricnych modulov.
   6 # 
   7 # =====================================================
   8 # Najprv import:
   9 from django.template import Template,Context
  10 # Vytvorime nasu prvu Template
  11 t=Template('{{pozdrav}}, {{koho}}')
  12 print t
  13 # Context sa vytvara zo slovnika:
  14 c1=Context({'pozdrav':'ahoj','koho':'svet'})
  15 print c1
  16 # A mozeme dosadit
  17 print t.render(c1)
  18 # Template sa da znovupouzit v inom kontexte
  19 # pri zmene Contextu ju teda netreba vytvarat znovu
  20 c2=Context({'pozdrav':'ahoj','koho':'slnko'})
  21 print t.render(c2)
  22 # Context nie je slovnikom, ale umoznuje slovnikove
  23 # operacie:
  24 c2['pozdrav']='dovi'
  25 print t.render(c2)
  26 # Hodnota v slovniku nemusi byt retazec, ale aj napr.
  27 # cislo:
  28 c2['koho']=3.14
  29 print c2
  30 print t.render(c2)
  31 # Nielen cislo, ale lubovolny objekt
  32 # Definujme nejaku triedu
  33 class Vec(object):
  34     def __init__(self,meno):
  35         self.meno=meno
  36     def __str__(self):
  37         # Prvy znak velkym pismenom
  38         return self.meno[0].upper()+self.meno[1:]
  39 
  40 # Vytvorme instanciu
  41 mes=Vec('mesiacik')
  42 # print vola __str__:
  43 print mes
  44 # Vytvorme kontext, ktory obsahuje objekt triedy Vec
  45 c3=Context({'pozdrav':'dobry vecer','koho':mes})
  46 # a mozeme renderovat
  47 print t.render(c3)

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2009-02-22 13:13:11, 1.3 KB) [[attachment:01_templates.py]]
  • [get | view] (2009-02-22 13:16:30, 1.9 KB) [[attachment:01_templates_out.py]]
 All files | Selected Files: delete move to page

You are not allowed to attach a file to this page.