|
269 | 269 | "outputs": [],
|
270 | 270 | "source": [
|
271 | 271 | "#| export\n",
|
272 |
| - "def _escape(s): return '' if s is None else escape(s) if isinstance(s, str) else s" |
| 272 | + "def _escape(s): return '' if s is None else s.__html__() if hasattr(s, '__html__') else escape(s) if isinstance(s, str) else s" |
273 | 273 | ]
|
274 | 274 | },
|
275 | 275 | {
|
|
322 | 322 | " res = f'{sp}<{stag}>\\n'\n",
|
323 | 323 | " res += ''.join(to_xml(c, lvl=lvl+2) for c in cs)\n",
|
324 | 324 | " if not isvoid: res += f'{sp}{cltag}\\n'\n",
|
325 |
| - " return res" |
| 325 | + " return res\n", |
| 326 | + "\n", |
| 327 | + "FT.__html__ = to_xml" |
326 | 328 | ]
|
327 | 329 | },
|
328 | 330 | {
|
|
358 | 360 | "print(h)"
|
359 | 361 | ]
|
360 | 362 | },
|
| 363 | + { |
| 364 | + "cell_type": "markdown", |
| 365 | + "id": "4713bd8d", |
| 366 | + "metadata": {}, |
| 367 | + "source": [ |
| 368 | + "Interoperability both directions with Django and Jinja using the [__html__() protocol](https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.escape)." |
| 369 | + ] |
| 370 | + }, |
361 | 371 | {
|
362 | 372 | "cell_type": "code",
|
363 |
| - "execution_count": null, |
| 373 | + "execution_count": 107, |
364 | 374 | "id": "798ae1d2",
|
365 | 375 | "metadata": {},
|
| 376 | + "outputs": [ |
| 377 | + { |
| 378 | + "name": "stdout", |
| 379 | + "output_type": "stream", |
| 380 | + "text": [ |
| 381 | + "<div><b>Hello from Django</b></div>\n", |
| 382 | + "\n", |
| 383 | + "<div>\n", |
| 384 | + " <p>Hello from fastcore <3</p>\n", |
| 385 | + "</div>\n", |
| 386 | + "\n" |
| 387 | + ] |
| 388 | + } |
| 389 | + ], |
| 390 | + "source": [ |
| 391 | + "class MockDjangoSafeString(str):\n", |
| 392 | + " def __html__(self):\n", |
| 393 | + " return self\n", |
| 394 | + "\n", |
| 395 | + "def mock_django_conditional_escape(s):\n", |
| 396 | + " return s.__html__() if hasattr(s, '__html__') else MockDjangoSafeString(escape(s))\n", |
| 397 | + "\n", |
| 398 | + "html_string_coming_from_django = MockDjangoSafeString('<b>Hello from Django</b>')\n", |
| 399 | + "print(to_xml(Div(html_string_coming_from_django)))\n", |
| 400 | + "\n", |
| 401 | + "print(mock_django_conditional_escape(Div(P('Hello from fastcore <3'))))" |
| 402 | + ] |
| 403 | + }, |
| 404 | + { |
| 405 | + "cell_type": "code", |
| 406 | + "execution_count": 108, |
| 407 | + "id": "5f0e91e0", |
| 408 | + "metadata": {}, |
366 | 409 | "outputs": [],
|
367 | 410 | "source": [
|
368 | 411 | "#| export\n",
|
|
0 commit comments