3

The following link allows for a way to render an HTML URL inside a python3 print() function within a Jupyter notebook code cell,

https://github.com/jupyterlab/jupyterlab/issues/7393#issue-510053776,

which defines a custom URL class,

"""URL Wrapper."""

from dataclasses import dataclass

@dataclass(frozen=True)
class Url:
    """Wrapper around a URL string to provide nice display in IPython environments."""

    __url: str

    def _repr_html_(self):
        """HTML link to this URL."""
        return f'<a href="{self.__url}">{self.__url}</a>' # problem here (*)

    def __str__(self):
        """Return the underlying string."""
        return self.__url

The commentator notes that one must use str(url()) to achieve the desired result.

Unlike (I think) the now built-in rendering of this, I am trying to use this custom class thus:

linker = lambda my_string: str(Url('https://www.google.com/%s' % my_string))
print('URL for my_string is here',linker('search'))

I would like the linker('search') to render as the string 'search' with the full hyperlink (https://www.google.com/search) behind. The built-in behaviour does not render 'search' but rather the full hyperlink, and I cannot find a way to successfully modify the custom class to do this. At line (*) above I have tried:

return f'<a href="{self.__url}">{self.__url}</a>'
return f'<a href="{self.__url}">{"test_text"}</a>'

etc. but so far in vain.

This answer helps a bit but doesn't explicitly use the print function as per my requirements: https://stackoverflow.com/a/43254984/1021819

What am I missing?

jtlz2
  • 7,700
  • 9
  • 64
  • 114

1 Answers1

4

This is a bit jank, but seems to work:


class RenderHyperlink(object):
    def __init__(self, key, link, *args):
        link = link + "/" if not link.endswith("/") else link
        
        for arg in args:
            link += arg + "/"
            
        self.__url = "<a href={}>{}</a>".format(link, key)
    
    def __repr__(self):
        from IPython.core.display import display, HTML
        display(HTML(self.__url))
        return "" # hacky way to return a string despite not returning anything


# notice that you can also add other parameters to the link
print(RenderHyperlink("search", "https://www.google.com/search", "hello"))

Output: The link points to "https://www.google.com/search/hello/" enter image description here

mahieyin-rahmun
  • 1,486
  • 1
  • 12
  • 20
  • Amazing, thank you! What is the best way to adapt this to allow for text on the same line before (or after) the `RenderHyperlink()` string? Right now if I do `print('Link:',RenderHyperlink(...))` then 'Link:' and the rendered hyperlink appear on two separate lines. – jtlz2 Feb 24 '21 at 12:44
  • 2
    Add `target=\"_blank\"` to self.__url to have the link open in a new tab instead of taking you away from the notebook. `self.__url = "{}".format(link, key)` – SlyGuy Oct 20 '21 at 17:29
  • The last line of `__init__()` should be `self.__url = '{}'.format(link, key)`? The double quotes are required for it to be proper HTML. – singhj Dec 13 '21 at 22:37