|
768 | 768 | ""
|
769 | 769 | ]
|
770 | 770 | },
|
| 771 | + { |
| 772 | + "cell_type": "markdown", |
| 773 | + "metadata": {}, |
| 774 | + "source": [ |
| 775 | + "## Passing URLs\n", |
| 776 | + "\n", |
| 777 | + "In the example above we have seen how to pass simple unicode strings to a HTML input element. However,\n", |
| 778 | + "certain HTML elements, like e.g. `<img/>`, `<iframe/>` or `<script/>` require URLs as input. Consider\n", |
| 779 | + "a widget embedding an `<iframe/>`. The widget has a `src` property that is connected to the `src`\n", |
| 780 | + "attribute of the `<iframe/>`. It is the ipywidget version of the built-in `IPython.display.IFrame(...)`.\n", |
| 781 | + "Like the built-in we'd like to support two forms:\n", |
| 782 | + "\n", |
| 783 | + "```python\n", |
| 784 | + "from ipyiframe import IFrame\n", |
| 785 | + "\n", |
| 786 | + "remote_url = IFrame(src='https://jupyter.org') # full HTTP URL\n", |
| 787 | + "local_file = IFrame(src='./local_file.html') # local file\n", |
| 788 | + "```\n", |
| 789 | + "\n", |
| 790 | + "Note, that the _second_ form is a path relative to the notebook file. Using this string as the `src`\n", |
| 791 | + "attribute of the `<iframe/>` is not going to work, because the browser will interpret it as a relative\n", |
| 792 | + "URL, relative to the browsers address bar. To transform the relative path into a valid file URL we use\n", |
| 793 | + "the utility funtion `resolveUrl(...)` in our javascript view class:\n", |
| 794 | + "\n", |
| 795 | + "```js\n", |
| 796 | + "export class IFrameView extends DOMWidgetView {\n", |
| 797 | + " render() {\n", |
| 798 | + " this.$iframe = document.createElement('iframe');\n", |
| 799 | + " this.el.appendChild(this.$iframe);\n", |
| 800 | + " this.src_changed();\n", |
| 801 | + " this.model.on('change:src', this.src_changed, this);\n", |
| 802 | + " }\n", |
| 803 | + "\n", |
| 804 | + " src_changed() {\n", |
| 805 | + " const url = this.model.get('src'); \n", |
| 806 | + " this.model.widget_manager.resolveUrl(url).then(resolvedUrl => { \n", |
| 807 | + " this.$iframe.src = resolvedUrl;\n", |
| 808 | + " }); \n", |
| 809 | + " }\n", |
| 810 | + "}\n", |
| 811 | + "```\n", |
| 812 | + "\n", |
| 813 | + "Invoking `this.model.widget_manager.resolveUrl(...)` returns a promise that resolves to the correct URL." |
| 814 | + ] |
| 815 | + }, |
771 | 816 | {
|
772 | 817 | "cell_type": "markdown",
|
773 | 818 | "metadata": {},
|
|
803 | 848 | ],
|
804 | 849 | "metadata": {
|
805 | 850 | "kernelspec": {
|
806 |
| - "display_name": "Python 3", |
| 851 | + "display_name": "Python 3 (ipykernel)", |
807 | 852 | "language": "python",
|
808 | 853 | "name": "python3"
|
809 | 854 | },
|
|
817 | 862 | "name": "python",
|
818 | 863 | "nbconvert_exporter": "python",
|
819 | 864 | "pygments_lexer": "ipython3",
|
820 |
| - "version": "3.9.1" |
| 865 | + "version": "3.9.9" |
821 | 866 | }
|
822 | 867 | },
|
823 | 868 | "nbformat": 4,
|
|
0 commit comments