How to set a custom Mosaic layout programmatically?

Initially, I thought the following code would work, but it didn't

 def set_mosaic_layout(obj):
     obj.contentLayout = '++contentlayout++custom/customLayout.html'
     obj.reindexObject(idxs=['layout', 'contentLayout'])

Is there any way I can set a custom Mosaic layout to an object? Otherwise, how can I set a custom Mosaic layout as the default view in Plone?

You need the adapted context to set the layout. I use this code for setting a mosaic layout on page create:

def set_mosaic_view(context):
    request = getRequest()
    safeWrite(context, request)
    if not ICustomThemeLayer.providedBy(request):  # pragma: no cover
    adapted_context = ILayoutAware(context, None)
    if adapted_context is not None and \
            adapted_context.contentLayout is None and \
            adapted_context.customContentLayout is None:
        # it is OK to use context to setLayout
        # use adapted_context for setting the MOSAIC layout
        if 'basic' not in _LAYOUT_CACHE:
            _LAYOUT_CACHE['basic'] = resolveResource('++contentlayout++web16theme/basic.html')
            # use adapted_context for setting the MOSAIC layout
        adapted_context.customContentLayout = _LAYOUT_CACHE.get('basic')

1 Like

I'm surprised. Exactly how did that not work? Tom is correct that there is also adapter for that, but the default adapter uses the same attributes that you set in your code. On old objects, you may need to reset custom inline layout attribute obj.customContentLayout = u'' to allow use of path in contentLayout instead.

Also, I don't recall there are indexes for those fields by default.

It is possible to set the default view of a content type to layout_view (in your custom content type ( or in /portal_types).

But is it possible to set 'which mosaic view', or is there no way around 'choosing it' after you add content ?

Default ”content layout” per content type can be set with registry configuration. I recall Mosaic’s registry.xml has example that defines the default for Document.