how to return a dictionary with template variables

1.1k views Asked by At

I'm working with the python web framework Bottle to generate html templates, and I want to pass a dictionary of template variables from the bottle server to the page. The documentation says that can be done like this:

@route(’/hello/<name>’)
@view(’hello_template’)
def hello(name=’World’):
  return dict(name=name)

And the @view template should have access to name. I want to do the same thing with a dictionary of search results, simplified here:

@get('/search')
@view('search')
def search():
    // load results
    // return results
    results = {'1': {'param1': 'val1', 'param2': 'val2', 'param3': 'val3'},
               '2': {'param1': 'val1', 'param2': 'val2', 'param3': 'val3'}
              }
    return results

But I get this error:

TypeError('template() keywords must be strings',)

With this traceback:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/bottle.py", line 862, in _handle
    return route.call(**args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/bottle.py", line 1732, in wrapper
    rv = callback(*a, **ka)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/bottle.py", line 3619, in wrapper
    return template(tpl_name, **tplvars)
TypeError: template() keywords must be strings

I could find similar questions but they all assumed that the params could be correctly passed, so I decided to ask. Thanks!

1

There are 1 answers

2
ayb On

I realy don't understand how you get this error, but anyway your code equals to:

@route('/search')
def search():
    return template('search', **results)

** means that template() function must unpack results to keywords arguments. In other words this code :

@route('/')
def index()
    return template(template_name, **{'a': 1, 'b': 2})

Absolutley equals this :

@route('/')
def index():
    return template(template_name, a=1, b=2)

And even equals this :

@route('/')
@view(template_name)
def index():
    return {'a': 1, 'b': 2}

Now ask yourself how do you access variable named 1 or 2 ( you trying to use this variables ) in your template ?

In your case template() function unpacks results to keyword arguments. If you want to pass results into template then use return dict(results=results)

But if you provide real code i think you'll get more detailed answer