A stack container for variable context
| 139 | |
| 140 | |
| 141 | class Context(BaseContext): |
| 142 | "A stack container for variable context" |
| 143 | |
| 144 | def __init__(self, dict_=None, autoescape=True, use_l10n=None, use_tz=None): |
| 145 | self.autoescape = autoescape |
| 146 | self.use_l10n = use_l10n |
| 147 | self.use_tz = use_tz |
| 148 | self.template_name = "unknown" |
| 149 | self.render_context = RenderContext() |
| 150 | # Set to the original template -- as opposed to extended or included |
| 151 | # templates -- during rendering, see bind_template. |
| 152 | self.template = None |
| 153 | super().__init__(dict_) |
| 154 | |
| 155 | @contextmanager |
| 156 | def bind_template(self, template): |
| 157 | if self.template is not None: |
| 158 | raise RuntimeError("Context is already bound to a template") |
| 159 | self.template = template |
| 160 | try: |
| 161 | yield |
| 162 | finally: |
| 163 | self.template = None |
| 164 | |
| 165 | def __copy__(self): |
| 166 | duplicate = super().__copy__() |
| 167 | duplicate.render_context = copy(self.render_context) |
| 168 | return duplicate |
| 169 | |
| 170 | def update(self, other_dict): |
| 171 | "Push other_dict to the stack of dictionaries in the Context" |
| 172 | if not hasattr(other_dict, "__getitem__"): |
| 173 | raise TypeError("other_dict must be a mapping (dictionary-like) object.") |
| 174 | if isinstance(other_dict, BaseContext): |
| 175 | other_dict = other_dict.dicts[1:].pop() |
| 176 | return ContextDict(self, other_dict) |
| 177 | |
| 178 | |
| 179 | class RenderContext(BaseContext): |
no outgoing calls