Code Blocks
Printing a snippet of a source code into HTML can be done in several ways with Pyreball.
Chapter Text Utils
already showed functions that can be used to
prepare code elements.
Another approach is to
use print_code_block()
function,
which prints the code block and brings some additional features.
The function wraps the values into <pre>
and <code>
elements and
uses highlight.js
library to highlight the syntax.
Basic usage is demonstrated in the following example.
import inspect
import pyreball as pb
def add(x, y):
return x + y
pb.print_code_block(inspect.getsource(add))
The language can be again set via syntax_highlight
parameter.
The supported languages are listed in the highlight.js'
Supported Languages table.
As with tables, a custom caption can be added and its position can be controlled through
caption
and caption_position
parameters.
The horizontal alignment of the code block can be also changed using align
parameter.
Last but not least, numbering can be turned off by setting numbered
to False.
import inspect
import pyreball as pb
def add(x, y):
return x + y
code_str = inspect.getsource(add)
pb.print_code_block(
code_str,
caption="My first function.",
caption_position="top",
align="left",
)
pb.print_code_block(code_str, numbered=False)
pb.print_code_block(
code_str,
caption="Third Time's the Charm.",
caption_position="bottom",
align="right",
numbered=False,
)