Attachment '01_templates_out.py'

Download

   1 gejza@debian:~/django/minidata$ python manage.py shell
   2 Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13)
   3 [GCC 4.3.2] on linux2
   4 Type "help", "copyright", "credits" or "license" for more information.
   5 (InteractiveConsole)
   6 >>> # Prve interaktivne sedenie: Django Templates
   7 >>> #
   8 >>> # Pouzitie: V existujucom django projekte
   9 >>> # treba spustit "manage.py shell".
  10 >>> # To zabezpeci natiahnutie patricnych modulov.
  11 >>> #
  12 >>> # =====================================================
  13 >>> # Najprv import:
  14 >>> from django.template import Template,Context
  15 >>> # Vytvorime nasu prvu Template
  16 >>> t=Template('{{pozdrav}}, {{koho}}')
  17 >>> print t
  18 <django.template.Template object at 0x84b606c>
  19 >>> # Context sa vytvara zo slovnika:
  20 >>> c1=Context({'pozdrav':'ahoj','koho':'svet'})
  21 >>> print c1
  22 [{'koho': 'svet', 'pozdrav': 'ahoj'}]
  23 >>> # A mozeme dosadit
  24 >>> print t.render(c1)
  25 ahoj, svet
  26 >>> # Template sa da znovupouzit v inom kontexte
  27 >>> # pri zmene Contextu ju teda netreba vytvarat znovu
  28 >>> c2=Context({'pozdrav':'ahoj','koho':'slnko'})
  29 >>> print t.render(c2)
  30 ahoj, slnko
  31 >>> # Context nie je slovnikom, ale umoznuje slovnikove
  32 >>> # operacie:
  33 >>> c2['pozdrav']='dovi'
  34 >>> print t.render(c2)
  35 dovi, slnko
  36 >>> # Hodnota v slovniku nemusi byt retazec, ale aj napr.
  37 >>> # cislo:
  38 >>> c2['koho']=3.14
  39 >>> print c2
  40 [{'koho': 3.1400000000000001, 'pozdrav': 'dovi'}]
  41 >>> print t.render(c2)
  42 dovi, 3.14
  43 >>> # Nielen cislo, ale lubovolny objekt
  44 >>> # Definujme nejaku triedu
  45 >>> class Vec(object):
  46 ...     def __init__(self,meno):
  47 ...         self.meno=meno
  48 ...     def __str__(self):
  49 ...         # Prvy znak velkym pismenom
  50 ...         return self.meno[0].upper()+self.meno[1:]
  51 ...
  52 >>> # Vytvorme instanciu
  53 >>> mes=Vec('mesiacik')
  54 >>> # print vola __str__:
  55 >>> print mes
  56 Mesiacik
  57 >>> # Vytvorme kontext, ktory obsahuje objekt triedy Vec
  58 >>> c3=Context({'pozdrav':'dobry vecer','koho':mes})
  59 >>> # a mozeme renderovat
  60 >>> print t.render(c3)
  61 dobry vecer, Mesiacik

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 copy to page

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