Is it possible to have Jinja2 ignore sections of a

2020-08-17 08:08发布

问题:

I added a facebook button to my page by copying/pasting the code they supply on their website.

It looks like this:

"http://www.facebook.com/dialog/feed?app_id={{fbapp_id}}&link={{link_url}}&message={{share_message|urlencode}}&display=popup&redirect_uri={{link_url}}  

As you can see, it's got the {} in there that Jinja looks for. However, being that I don't want any of the above code replaced with anything, is there something I can add into my template which tells Jinja to ignore everything between the delimiters?

Python Handler:

class MainHandler(webapp2.RequestHandler):
    def get(self):
        template = JINJA_ENV.get_template('index.html')
        self.response.write(template.render(None))

回答1:

You can usually find that information in the documentation, under "Escaping" or similar. In this case, you can either output the delimiter with a variable expression:

{{ '{{' }}

Or you can use the raw block, for longer stretches of code:

{% raw %}
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
{% endraw %}


回答2:

This question is old but I recently had the same issue. If you setup Jinja2 Environment to use undefined=jinja2.DebugUndefined it will ignore missing parameters and leave them as if a new Jinja template. Useful for say multi-stage parsing and u can run logging as well to know when variables have not been defined:

import logging
from Jinja2 import DebugUndefined

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
undefined_logging = jinja2.make_logging_undefined(logger=logger, base=DebugUndefined)
jinja_env = jinja2.Environment(loader=FileSystemLoader, undefined=undefined_logging)
print(jinja2.from_string("Hello {{ worldarg }}")

This will result in a logger message such as
[date time] WARNING [<module>:lineno] Template variable warning worldarg is undefined
Hello {{ worldarg }}

Template in will have jinja rendered for passed parameters but unaltered for undefined. NOTE: This will unlikely resolve missing templates or macros defined by the routine though but standard {{ x }} types should be logged and unaltered. *Logging is also subject to how its configured as well!

Options also exist for StrictUndefined (results in exception and template processing to stop) or Undefined results in parameters passed to be removed and fields blank where expected without errors being returned to calling function.



标签: python jinja2