2013-01-11 12 views
7

Sto provando a creare un modello html in python usando Jinja2. Ho una cartella di modelli con il mio 'template.html' ma non so come gestire ambienti o caricatori di pacchetti.HTML templating con Jinja2 - Lost

Ho installato Jinja2 utilizzando easy_python e ho eseguito il seguente script.

from jinja2 import Environment, PackageLoader 
env = Environment(loader=PackageLoader('yourapplication', 'templates')) 
template = env.get_template('mytemplate.html') 
print template.render() 

Ho ricevuto il seguente errore perché non so come definire un pacchetto/modulo. Per favore aiutami Voglio solo creare un modello semplice.

File "log_manipulationLL.py", line 291, in <module> 
env = Environment(loader=PackageLoader('yourapplication', 'templates')) 
File "/usr/local/lib/python2.7/dist-packages/Jinja2-2.6-py2.7.egg/jinja2/loaders.py", line 216, in __init__ 
provider = get_provider(package_name) 
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 213, in get_provider 
__import__(moduleOrReq) 
ImportError: No module named yourapplication 

risposta

8

PackageLoader aspetta un modulo Python reale utilizzando la sintassi del punto regolare. Per esempio, se la vostra struttura è simile al seguente:

myapp/ 
    __init__.py 
    … 
    templates/ 
    mytemplate.html 

Si dovrebbe usare myapp come il nome del modulo.

+0

È possibile lasciarlo vuoto. Vedi http://docs.python.org/2/tutorial/modules.html#packages – patrys

+0

Oh grazie mille! – pombo

8

Ho risolto questo problema utilizzando il seguente codice:

env = Environment(loader=PackageLoader('scriptname', 
             templatesPath)) 

in cui questo codice è nel file scriptname.py.

Non sono sicuro che la mia risposta sia pertinente, ma mi chiedevo che forse qualcuno potrebbe trovare utile questa risposta. Se mi sbaglio, per favore fatemelo sapere.

+1

Il caricatore di pacchetti chiama 'scriptname.py'. Se si inizializza il loader del pacchetto, il codice verrà chiamato una seconda volta. – Henrik

8

Se non si desidera o bisogno di un pacchetto di Python, probabilmente dovreste usare un FileSystemLoader invece, in questo modo:

from jinja2 import Environment, FileSystemLoader, select_autoescape 
env = Environment(
    loader=FileSystemLoader('file/path/'), 
    autoescape=select_autoescape(['html', 'xml']), 
) 
1

PackageLoader è definita in questo modo:

class PackageLoader(BaseLoader): 
    """Load templates from python eggs or packages. It is constructed with 
    the name of the python package and the path to the templates in that 
    package:: 

     loader = PackageLoader('mypackage', 'views') 

    If the package path is not given, ``'templates'`` is assumed. 

    Per default the template encoding is ``'utf-8'`` which can be changed 
    by setting the `encoding` parameter to something else. Due to the nature 
    of eggs it's only possible to reload templates if the package was loaded 
    from the file system and not a zip file. 
    """ 

E poi il __init__() metodo è il seguente:

def __init__(self, package_name, package_path='templates', 
      encoding='utf-8'): 

Questo ci fa notare che una st ructure come questo:

myapp/ 
    __init__.py 
    ... 
    templates/ 
    mytemplate.html 

avrà lo stesso PackageLoader un'istanza con entrambe queste dichiarazioni:

PackageLoader('myapp') 
PackageLoader('myapp', 'templates') 

E così, se si esegue dal percorso myapp/, è quindi solo bisogno di dire:

PackageLoader('templates', '') 

In modo che ci vuole solo templates/ come il percorso. Se lasci vuoto il secondo argomento, cercherà di trovare i modelli in templates/templates.

Infine, è possibile controllare ciò che è stato caricato utilizzando il metodo list_templates():

PackageLoader('templates', '').list_templates()