How to define widgets with default values in Apost

2019-08-02 07:52发布

问题:

I want to add a widget that can't be removed from the page and contain some default text when it is not defined explicitly. I thought it should work something like this:

{{ 
   apos.singleton(data.page, 'headerTitle', 'apostrophe-rich-text', {
       def: 'Default Title'
   }) 
}}

Is there any way to do this with apostrophe widgets or I should create custom one?

回答1:

Creating your own widgets is pretty standard practice in Apostrophe but it doesn't address what to do if there is no widget yet in a singleton.

You can disable the removal of the singleton like this:

{{
  apos.singleton(data.page, 'headerTitle', 'apostrophe-rich-text', {
    controls: {
      removable: false,
      movable: false
    }
  })
}}

However an editor still has to click to initially add the widget to the page for each page.

So use this technique to provide default markup:

{% if apos.areas.isEmpty(data.page, 'headerTitle') %}
  <h4>Default Title</h4>
{% endif %}
{{
  apos.singleton(data.page, 'headerTitle', 'apostrophe-rich-text', {
    controls: {
      removable: false,
      movable: false
    }
  })
}}