Block helpers#
plone_client.blocks builds the blocks of Volto pages, and walks the ones a site returns.
None of these functions sends a request.
Content model describes the fields they produce, and Build any block shows them at work.
Function |
Returns |
|---|---|
A new block id. |
|
|
|
A block that shows the title of the item. |
|
A block that shows the description of the item. |
|
A slate block with one plain paragraph. |
|
Any block, from its type and its data. |
|
A block that holds other blocks. |
|
A |
|
A card that links to one item. |
|
Blocks for Markdown or HTML. |
|
A block in the shape Volto stores. |
|
|
|
Field values with normalized blocks. |
|
What holds a block. |
|
A short view of blocks. |
|
Every block, nested ones included. |
|
Every link inside a value. |
|
The shape of a |
|
Several |
|
A |
Build blocks#
new_id and build give blocks new ids.
from plone_client import blocks
print(len(blocks.new_id()))
page = blocks.build(blocks.title(), blocks.text("Hello!"))
print(sorted(page))
print([block["@type"] for block in page["blocks"].values()])
print(page["blocks_layout"]["items"] == list(page["blocks"]))
36
['blocks', 'blocks_layout']
['title', 'slate']
True
title, description, and text build the blocks of a simple page.
text takes plain text, not Markdown, and collapses whitespace.
from plone_client import blocks
print(blocks.title())
print(blocks.description())
print(blocks.text("Five *stars*\nand more."))
{'@type': 'title'}
{'@type': 'description'}
{'@type': 'slate', 'plaintext': 'Five *stars* and more.', 'value': [{'type': 'p', 'children': [{'text': 'Five *stars* and more.'}]}]}
block builds any block from its @type and its data.
from plone_client import blocks
print(blocks.block("listing", querystring={"query": [], "sort_on": "effective"}))
{'querystring': {'query': [], 'sort_on': 'effective'}, '@type': 'listing'}
teaser links to one item, and title stores a title with the link.
Other keyword arguments become data of the block.
from plone_client import blocks
print(blocks.teaser("/news/release-6-2", "Release", overwrite=True))
{'href': [{'@id': '/news/release-6-2', 'title': 'Release'}], 'overwrite': True, '@type': 'teaser'}
container and grid hold other blocks in blocks and blocks_layout.
Keyword arguments become the data of the block itself.
from plone_client import blocks
section = blocks.container("accordion", blocks.text("One."), headline="FAQ")
print(sorted(section), section["@type"], section["headline"])
row = blocks.grid(blocks.teaser("/news"), blocks.teaser("/about"))
print(row["@type"], len(row["blocks"]))
['@type', 'blocks', 'blocks_layout', 'headline'] accordion FAQ
gridBlock 2
Convert Markdown and HTML#
convert needs the markdown extra, on Python 3.12 or later.
before adds blocks before the converted ones, and the second argument chooses html.
from plone_client import blocks
page = blocks.convert("## Heading\n\nA paragraph.\n", before=[blocks.title()])
print([block["@type"] for block in page["blocks"].values()])
page = blocks.convert("<p>From <em>HTML</em>.</p>", "html")
print([block["plaintext"] for block in page["blocks"].values()])
['title', 'slate', 'slate']
['From HTML.']
Repair blocks#
normalize accepts the shortcuts of hand-written blocks: a string href, and a list of blocks inside a container.
from plone_client import blocks
print(blocks.normalize({"@type": "teaser", "href": "/news"}))
grid = blocks.normalize({"@type": "gridBlock", "blocks": [{"@type": "teaser", "href": "/news"}]})
print(len(grid["blocks"]), len(grid["blocks_layout"]["items"]))
{'@type': 'teaser', 'href': [{'@id': '/news'}]}
1 1
tidy makes blocks and blocks_layout agree: it drops unknown and repeated ids, adds missing ones at the end, and moves the title first.
from plone_client import blocks
found = {"a": {"@type": "slate"}, "b": {"@type": "title"}, "c": {"@type": "image"}}
print(blocks.tidy(found, {"items": ["a", "a", "gone", "b"]})["blocks_layout"])
{'items': ['b', 'a', 'c']}
prepare applies both to the field values of an item, and takes blocks as a list.
from plone_client import blocks
data = blocks.prepare({"title": "Hello", "blocks": [{"@type": "title"}]})
print(sorted(data), data["title"])
['blocks', 'blocks_layout', 'title'] Hello
Walk blocks#
The examples below use a page with a grid inside.
item = {
"blocks": {
"top": {"@type": "title"},
"row": {
"@type": "gridBlock",
"headline": "Latest",
"blocks": {"card": {"@type": "teaser", "href": [{"@id": "/news"}]}},
"blocks_layout": {"items": ["card"]},
},
},
"blocks_layout": {"items": ["top", "row"]},
}
outline gives a short view, iter_blocks goes through every block, depth first, iter_links finds the links, and locate finds what holds a block.
from plone_client import blocks
from sample import item
print(blocks.outline(item["blocks"], item["blocks_layout"]))
print([block_id for block_id, _ in blocks.iter_blocks(item["blocks"], item["blocks_layout"])])
print(list(blocks.iter_links(item["blocks"])))
print(blocks.locate(item, "card")["@type"])
[{'id': 'top', '@type': 'title'}, {'id': 'row', '@type': 'gridBlock', 'text': 'Latest', 'blocks': [{'id': 'card', '@type': 'teaser'}]}]
['top', 'row', 'card']
['/news']
gridBlock
Choose block types#
A blocks setting says which block types convert() produces.
Keys are block types, and values are True, False, or a mapping of options.
Manage profiles shows how to set it for a site.
from plone_client import blocks
print(blocks.check_setting({"codeBlock": True}))
print(blocks.merge_settings({"codeBlock": True, "table": False}, {"codeBlock": False}))
print(blocks.validate_setting({"codeBlock": {"style": "light"}}))
try:
blocks.check_setting({"codeBlock": "yes"})
except ValueError as error:
print(error)
{'codeBlock': True}
{'codeBlock': False, 'table': False}
{'codeBlock': {'style': 'light'}}
Setting of block type codeBlock must be true, false or a mapping of options, not 'yes'
Module#
Helpers for Volto blocks: build them, walk them, find their links.
A page built with Volto stores its content in two fields: blocks, a
mapping of block ids to block data, and blocks_layout, whose items
list the block ids in order. A page without both renders empty.
Example:
from plone_client import blocks
page = blocks.build(
blocks.title(),
blocks.description(),
blocks.text("Hello!"),
)
site.content.create("/", "Document", title="Hello", **page)
Blocks this module has no helper for, such as those of an add-on, are built
with block(), and blocks that hold other blocks with container().
A grid of four teasers:
paths = ["/news/a", "/news/b", "/news/c", "/news/d"]
page = blocks.build(
blocks.title(),
blocks.grid(*(blocks.teaser(path) for path in paths)),
)
Markdown and HTML can be converted to blocks with convert().
- plone_client.blocks.BlocksSetting#
Which block types
convert()produces, keyed by their@type:Trueor a mapping of options enables a block type,Falsedisables it. Block types left out keep the converter’s default.
- plone_client.blocks.LINK_KEYS = frozenset({'href', 'link', 'preview_image_link', 'url'})#
Keys whose string values are links.
- plone_client.blocks.new_id()[source]#
A fresh block id.
- Returns:
A random UUID, the way Volto writes block ids.
- Return type:
- plone_client.blocks.text(value)[source]#
A text block with one plain paragraph.
The value is plain text, not Markdown:
*and<are kept as they are. Runs of whitespace, newlines included, become one space, as in an HTML paragraph. Withcollective.html2blocksinstalled, it builds the block, as it does forconvert(); without it, the block is built here, the same way.
- plone_client.blocks.block(block_type, /, **data)[source]#
Any block, given its type and its data.
For blocks this module has no helper for, such as those of an add-on.
client.block_typesdescribes the data each block of a site takes.
- plone_client.blocks.container(block_type, /, *items, **data)[source]#
A block that holds other blocks, such as a grid.
The blocks inside get their own
blocksandblocks_layout, as a page has; seebuild().
- plone_client.blocks.grid(*items, **data)[source]#
A Volto grid, which shows its blocks side by side.
Volto allows up to four blocks in a grid, unless the site changes that.
A teaser: a card linking to one item, with its title and image.
The teaser shows the title, description, and image of the target, and follows later changes to it.
- plone_client.blocks.normalize(item)[source]#
A block written by hand or by a model, in the shape Volto stores.
A string
hrefbecomes the list of links that teasers, buttons and images keep ([{"@id": …}]). Blocks inside a container may be given as a list, in order: they get ids and ablocks_layout. Blocks inside given as a mapping are normalized too, and their layout is tidied withtidy().
- plone_client.blocks.tidy(blocks, layout=None)[source]#
blocksand ablocks_layoutthat agree with each other.Layout ids that name no block are dropped, and so are repeated ones; blocks missing from the layout are added at the end. A title block is moved first, where Volto expects it. Other keys of the layout are kept.
- plone_client.blocks.locate(holder, block_id)[source]#
What holds a block: an item, or the container block it is in.
- plone_client.blocks.TEXT_KEYS = ('plaintext', 'title', 'headline', 'alt')#
Keys whose value is shown as the text of a block in
outline().
- plone_client.blocks.outline(blocks, layout=None, *, width=60)[source]#
A short view of blocks: their ids, types and the start of their text.
- Parameters:
- Returns:
One entry per block, in layout order, with
id,@type, maybetext, andblocksfor the blocks inside a container.- Return type:
- plone_client.blocks.prepare(data)[source]#
Field values whose blocks are normalized and tidied.
blocksmay be a list of blocks, in order, instead of a mapping: they get ids and ablocks_layout, and a givenblocks_layoutis ignored. Each block goes throughnormalize(), and the layout throughtidy(). Values withoutblocksare returned as they are.
- plone_client.blocks.check_setting(setting)[source]#
The shape of a
blockssetting, checked.Block type names and options are checked by
validate_setting(), which needscollective.html2blocks; this only checks the shape, so a profile can be read without it.
- plone_client.blocks.merge_settings(*settings)[source]#
blockssettings merged, block type by block type.A later setting replaces what an earlier one says about a block type, options included, and keeps what it says about the others. A site’s setting followed by the setting of one call gives the call’s choices, with the site’s for the rest.
- plone_client.blocks.validate_setting(setting)[source]#
A
blockssetting, checked against the converter’s block types.Run it before a task that converts several sources, so that a mistake stops the task before anything is sent.
- Parameters:
setting (Mapping[str, bool | Mapping[str, Any]] | None) – The setting.
- Returns:
The setting, as plain dicts.
- Raises:
ValueError – For an unknown block type or option, a value of the wrong type, or disabling a block type the converter needs.
PloneConfigurationError – If
collective.html2blocksis not installed and the setting is not empty.
- Return type:
- plone_client.blocks.convert(source, source_format='markdown', *, before=(), blocks=None)[source]#
Blocks for Markdown or HTML, converted by
collective.html2blocks.Paragraphs, headings, lists and quotes become text (
slate) blocks; images, videos and tables get blocks of their own.blockschooses the block types, for example to turn code fences into thecodeBlockof a site that has it:blocks.convert(source, blocks={"codeBlock": {"style": "light"}})
Needs the
markdownextra (Python 3.12 or later):pip install 'plone-client[markdown]'
- Parameters:
source (str) – The Markdown or HTML.
source_format (Literal['markdown', 'html']) –
markdownorhtml.before (Iterable[Mapping[str, Any]]) – Blocks to put before the converted ones, such as
title()anddescription().blocks (Mapping[str, bool | Mapping[str, Any]] | None) – Which block types to produce, and their options; see
BlocksSetting.
- Returns:
blocksandblocks_layout, asbuild()returns them.- Raises:
PloneConfigurationError – If
collective.html2blocksis not installed.ValueError – If the format is unknown, or for an invalid
blockssetting.
- Return type:
- plone_client.blocks.iter_blocks(blocks, layout=None)[source]#
Every block, nested ones included, depth first.
Blocks are visited in layout order. Container blocks (grids, columns, accordions…) keep their children either in their own
blocksandblocks_layoutor insidedata; both are followed. Blocks missing from the layout come last.