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

new_id()

A new block id.

build()

blocks and blocks_layout for blocks in order.

title()

A block that shows the title of the item.

description()

A block that shows the description of the item.

text()

A slate block with one plain paragraph.

block()

Any block, from its type and its data.

container()

A block that holds other blocks.

grid()

A gridBlock.

teaser()

A card that links to one item.

convert()

Blocks for Markdown or HTML.

normalize()

A block in the shape Volto stores.

tidy()

blocks and a blocks_layout that agree.

prepare()

Field values with normalized blocks.

locate()

What holds a block.

outline()

A short view of blocks.

iter_blocks()

Every block, nested ones included.

iter_links()

Every link inside a value.

check_setting()

The shape of a blocks setting, checked.

merge_settings()

Several blocks settings, merged.

validate_setting()

A blocks setting, checked against the converter.

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: True or a mapping of options enables a block type, False disables it. Block types left out keep the converter’s default.

alias of Mapping[str, bool | Mapping[str, Any]]

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:

str

plone_client.blocks.build(*items)[source]#

blocks and blocks_layout for blocks in order.

Parameters:

items (Mapping[str, Any]) – Block data, each with an @type.

Returns:

A mapping with blocks and blocks_layout, ready to merge into the data of an item.

Return type:

dict[str, Any]

plone_client.blocks.title()[source]#

A title block, which shows the item’s title.

Returns:

The block.

Return type:

dict[str, Any]

plone_client.blocks.description()[source]#

A description block, which shows the item’s description.

Returns:

The block.

Return type:

dict[str, Any]

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. With collective.html2blocks installed, it builds the block, as it does for convert(); without it, the block is built here, the same way.

Parameters:

value (str) – The text.

Returns:

A slate block.

Return type:

dict[str, Any]

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_types describes the data each block of a site takes.

Parameters:
  • block_type (str) – The block’s @type, such as listing.

  • data (Any) – The block’s data.

Returns:

The block.

Return type:

dict[str, Any]

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 blocks and blocks_layout, as a page has; see build().

Parameters:
  • block_type (str) – The block’s @type, such as gridBlock.

  • items (Mapping[str, Any]) – The blocks inside, in order.

  • data (Any) – The container’s own data, such as a headline.

Returns:

The block.

Return type:

dict[str, Any]

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.

Parameters:
  • items (Mapping[str, Any]) – The blocks inside, in order, such as teaser() blocks.

  • data (Any) – The grid’s own data, such as a headline.

Returns:

A gridBlock block.

Return type:

dict[str, Any]

plone_client.blocks.teaser(target, title='', **data)[source]#

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.

Parameters:
  • target (str) – Site path or URL of the item, or a URL outside the site.

  • title (str) – Title to store with the link.

  • data (Any) – More data, such as overwrite and description.

Returns:

A teaser block.

Return type:

dict[str, Any]

plone_client.blocks.normalize(item)[source]#

A block written by hand or by a model, in the shape Volto stores.

A string href becomes 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 a blocks_layout. Blocks inside given as a mapping are normalized too, and their layout is tidied with tidy().

Parameters:

item (Mapping[str, Any]) – The block data.

Returns:

A new block.

Raises:

ValueError – If the block, or one inside it, has no @type.

Return type:

dict[str, Any]

plone_client.blocks.tidy(blocks, layout=None)[source]#

blocks and a blocks_layout that 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.

Parameters:
Returns:

blocks and blocks_layout, as build() returns them.

Return type:

dict[str, Any]

plone_client.blocks.locate(holder, block_id)[source]#

What holds a block: an item, or the container block it is in.

Parameters:
  • holder (Mapping[str, Any]) – The data of an item, or a block, with blocks.

  • block_id (str) – Id of the block to find, at any depth.

Returns:

The mapping whose blocks holds the block, or None.

Return type:

dict[str, Any] | None

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:
  • blocks (Mapping[str, Any] | None) – The blocks of an item or of a container block.

  • layout (Mapping[str, Any] | None) – The matching blocks_layout.

  • width (int) – Longest text to show.

Returns:

One entry per block, in layout order, with id, @type, maybe text, and blocks for the blocks inside a container.

Return type:

list[dict[str, Any]]

plone_client.blocks.prepare(data)[source]#

Field values whose blocks are normalized and tidied.

blocks may be a list of blocks, in order, instead of a mapping: they get ids and a blocks_layout, and a given blocks_layout is ignored. Each block goes through normalize(), and the layout through tidy(). Values without blocks are returned as they are.

Parameters:

data (Mapping[str, Any]) – Field values of an item.

Returns:

New field values.

Raises:

ValueError – If a block has no @type.

Return type:

dict[str, Any]

plone_client.blocks.check_setting(setting)[source]#

The shape of a blocks setting, checked.

Block type names and options are checked by validate_setting(), which needs collective.html2blocks; this only checks the shape, so a profile can be read without it.

Parameters:

setting (Any) – The setting, such as {"codeBlock": {"style": "light"}}.

Returns:

A copy, as plain dicts.

Raises:

ValueError – If it is not a mapping of block types to True, False or a mapping of options.

Return type:

dict[str, bool | dict[str, Any]]

plone_client.blocks.merge_settings(*settings)[source]#

blocks settings 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.

Parameters:

settings (Mapping[str, bool | Mapping[str, Any]] | None) – The settings, earliest first; None is skipped.

Returns:

The merged setting.

Raises:

ValueError – If a setting has the wrong shape.

Return type:

dict[str, Any]

plone_client.blocks.validate_setting(setting)[source]#

A blocks setting, 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.html2blocks is not installed and the setting is not empty.

Return type:

dict[str, Any]

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. blocks chooses the block types, for example to turn code fences into the codeBlock of a site that has it:

blocks.convert(source, blocks={"codeBlock": {"style": "light"}})

Needs the markdown extra (Python 3.12 or later):

pip install 'plone-client[markdown]'
Parameters:
Returns:

blocks and blocks_layout, as build() returns them.

Raises:
Return type:

dict[str, Any]

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 blocks and blocks_layout or inside data; both are followed. Blocks missing from the layout come last.

Parameters:
  • blocks (Mapping[str, Any] | None) – The blocks of an item or of a container block.

  • layout (Mapping[str, Any] | None) – The matching blocks_layout.

Returns:

Pairs of block id and block data.

Return type:

Iterator[tuple[str, dict[str, Any]]]

Every link inside a block, or inside any value.

Finds string values of url, href, link and preview_image_link keys, and the @id of the objects that object browser widgets store in lists ("href": [{"@id": …}]).

Parameters:

node (Any) – A block, a mapping of blocks, or any JSON value.

Returns:

Each link, in document order.

Return type:

Iterator[str]