Skip to content

esparto.design.content

Info

Content classes will usually be inferred from the content object type. They may be accessed via the top level module if required.

import esparto as es

# Create some new Markdown text
markdown = es.Markdown("Example _markdown_ text.")

Content

Template for Content elements.

Attributes:

Name Type Description
content Any

Item to be included in the page - should match the encompassing Content class.

display(self)

Display rendered content in a Jupyter Notebook cell.

Source code in esparto/design/content.py
def display(self) -> None:
    """Display rendered content in a Jupyter Notebook cell."""
    nb_display(self)

to_html(self, **kwargs)

Convert content to HTML string.

Returns:

Type Description
str

str: HTML string.

Source code in esparto/design/content.py
@abstractmethod
def to_html(self, **kwargs: bool) -> str:
    """Convert content to HTML string.

    Returns:
        str: HTML string.

    """
    raise NotImplementedError


Markdown

Markdown text content.

Parameters:

Name Type Description Default
text str

Markdown text to be added to document.

required

to_html(self, **kwargs)

Convert content to HTML string.

Returns:

Type Description
str

str: HTML string.

Source code in esparto/design/content.py
def to_html(self, **kwargs: bool) -> str:
    html = md.markdown(self.content, extensions=["extra", "smarty"])
    html = f"{html}\n"
    html = f"<div class='es-markdown'>\n{html}\n</div>"
    return html

DataFramePd

Pandas DataFrame to be converted to table.

Parameters:

Name Type Description Default
df pd.DataFrame

A Pandas DataFrame

required
index bool

If True, render the DataFrame index. (default = True)

required
col_space str, int

Minimum column width in CSS units. Use int for pixels. (default = 0)

required

Attributes:

Name Type Description
css_classes List[str]

CSS classes applied to the HTML output.

to_html(self, **kwargs)

Convert content to HTML string.

Returns:

Type Description
str

str: HTML string.

Source code in esparto/design/content.py
def to_html(self, **kwargs: bool) -> str:
    html: str = self.content.to_html(
        index=self.index,
        border=0,
        col_space=self.col_space,
        classes=self.css_classes,
    )
    html = f"<div class='table-responsive es-table'>{html}</div>"
    return html

FigureMpl

Matplotlib figure.

Parameters:

Name Type Description Default
figure plt.Figure

A Matplotlib figure.

required
output_format str

'svg' or 'png'. (default = None)

required
pdf_figsize tuple, float

Set figure size for PDF output. (default = None) Accepts a tuple of (height, width) or a float to use as scale factor.

required

to_html(self, **kwargs)

Convert content to HTML string.

Returns:

Type Description
str

str: HTML string.

Source code in esparto/design/content.py
def to_html(self, **kwargs: bool) -> str:

    if kwargs.get("notebook_mode"):
        output_format = options.matplotlib.notebook_format
    else:
        output_format = self.output_format

    if kwargs.get("pdf_mode") and self.pdf_figsize:
        if isinstance(self.pdf_figsize, float):
            figsize = self.pdf_figsize * self._original_figsize
        else:
            figsize = self.pdf_figsize
        self.content.set_size_inches(*figsize)

    if output_format == "svg":

        string_buffer = StringIO()
        self.content.savefig(string_buffer, format="svg")
        string_buffer.seek(0)
        xml = string_buffer.read()

        dpi = 96
        fig_width, fig_height = (
            int(val * dpi) for val in self.content.get_size_inches()
        )

        if kwargs.get("pdf_mode"):
            xml = responsive_svg_mpl(
                xml, width=int(fig_width), height=int(fig_height)
            )
            temp_file = Path(options._pdf_temp_dir) / f"{uuid4()}.svg"
            temp_file.write_text(xml)
            inner = (
                "<object type='image/svg+xml' width='100%' height='100%' "
                f"data='{temp_file.name}'></object>\n"
            )
        else:
            xml = responsive_svg_mpl(xml)
            inner = xml

        html = (
            f"<div class='es-matplotlib-figure' style='width: min({fig_width}px, 100%);'>"
            f"{inner}\n</div>\n"
        )

        # Reset figsize in case it was changed
        self.content.set_size_inches(*self._original_figsize)

        return html

    # If not svg:
    bytes_buffer = BytesIO()
    self.content.savefig(bytes_buffer, format="png")
    bytes_buffer.seek(0)
    return Image(bytes_buffer).to_html()

FigureBokeh

Bokeh object to be rendered as an interactive plot.

Parameters:

Name Type Description Default
figure bokeh.layouts.LayoutDOM

A Bokeh object.

required
layout_attributes dict

Attributes set on figure. (default = None)

required

to_html(self, **kwargs)

Convert content to HTML string.

Returns:

Type Description
str

str: HTML string.

Source code in esparto/design/content.py
def to_html(self, **kwargs: bool) -> str:

    if self.layout_attributes:
        for key, value in self.layout_attributes.items():
            setattr(self.content, key, value)

    # Bokeh to PDF is experimental and untested
    if kwargs.get("pdf_mode"):  # pragma: no cover
        from bokeh.io import export_svg  # type: ignore

        temp_file = Path(options._pdf_temp_dir) / f"{uuid4()}.svg"
        export_svg(self.content, filename=str(temp_file))
        html = f"<img src='{temp_file.name}' width='100%' height='auto'>\n"
        return html

    html, js = components(self.content)

    # Remove outer <div> tag so we can give our own attributes
    html = remove_outer_div(html)

    fig_width = self.content.properties_with_values().get("width", 1000)

    return (
        "<div class='es-bokeh-figure' "
        f"style='width: min({fig_width}px, 100%);'>"
        f"\n{html}\n{js}\n</div>"
    )

FigurePlotly

Plotly figure to be rendered as an interactive plot.

Parameters:

Name Type Description Default
figure plotly.graph_objs._figure.Figure

A Plotly figure.

required
layout_args dict

Args passed to figure.update_layout(). (default = None)

required

to_html(self, **kwargs)

Convert content to HTML string.

Returns:

Type Description
str

str: HTML string.

Source code in esparto/design/content.py
def to_html(self, **kwargs: bool) -> str:

    if self.layout_args:
        self.content.update_layout(**self.layout_args)

    # Default width is 700, default height is 450
    fig_width: int = getattr(self.content, "width", 700)

    if kwargs.get("pdf_mode"):
        temp_file = Path(options._pdf_temp_dir) / f"{uuid4()}.svg"
        self.content.write_image(str(temp_file))
        inner = f"<img src='{temp_file.name}' width='100%' height='auto'>"

    else:
        inner = plotly_to_html(
            self.content, include_plotlyjs=False, full_html=False
        )
        # Remove outer <div> tag so we can give our own attributes.
        inner = remove_outer_div(inner)

    html = f"<div class='es-plotly-figure' style='width: min({fig_width}px, 100%);'>{inner}\n</div>"

    # Reset layout in case it was changed
    self.content.update_layout(self._original_layout)

    return html

Image

Image content.

Can be read from a filepath, PIL.Image object, or from bytes..

Parameters:

Name Type Description Default
image str, Path, PIL.Image, BytesIO

Image data.

required
caption str

Image caption (default = None)

required
alt_text str

Alternative text. (default = None)

required
scale float

Scale image by proportion. (default = None)

required
set_width int

Set width in pixels. (default = None)

required
set_height int

Set height in pixels. (default = None)

required

rescale(self, scale)

Resize the image by a scaling factor.

Parameters:

Name Type Description Default
scale float

Scaling ratio.

required
Source code in esparto/design/content.py
def rescale(self, scale: float) -> None:
    """Resize the image by a scaling factor.

    Args:
        scale (float): Scaling ratio.

    """
    self._scale = scale

set_height(self, height)

Set height of image.

Parameters:

Name Type Description Default
height int

New height in pixels.

required
Source code in esparto/design/content.py
def set_height(self, height: int) -> None:
    """Set height of image.

    Args:
        height (int): New height in pixels.

    """
    self._height = height

set_width(self, width)

Set width of image.

Parameters:

Name Type Description Default
width int

New width in pixels.

required
Source code in esparto/design/content.py
def set_width(self, width: int) -> None:
    """Set width of image.

    Args:
        width (int): New width in pixels.

    """
    self._width = width

to_html(self, **kwargs)

Convert content to HTML string.

Returns:

Type Description
str

str: HTML string.

Source code in esparto/design/content.py
def to_html(self, **kwargs: bool) -> str:
    image_bytes = image_to_bytes(self.content)
    image_encoded = bytes_to_base64(image_bytes)

    width = f"min({self._width}, 100%)" if self._width else "auto"
    height = f"min({self._height}, 100%)" if self._height else "auto"
    scale = f"transform: scale({self._scale});" if self._scale else ""

    html = (
        "<figure class='es-figure'>"
        "<img class='img-fluid figure-img rounded es-image' "
        f"style='width: {width}; height: {height}; {scale}' "
        f"alt='{self.alt_text}' "
        f"src='data:image/png;base64,{image_encoded}'>"
    )

    if self.caption:
        html += f"<figcaption class='figure-caption'>{self.caption}</figcaption>"

    html += "</figure>"

    return html

RawHTML

Raw HTML content.

Parameters:

Name Type Description Default
html str

HTML string.

required

to_html(self, **kwargs)

Convert content to HTML string.

Returns:

Type Description
str

str: HTML string.

Source code in esparto/design/content.py
def to_html(self, **kwargs: bool) -> str:
    return self.content