How to programmatically print a webform block with caching enabled?
The Dynamic Page Cache needs to placeholder the dynamic part and it can only do so when it is built in a lazy builder:
/mymodule/src/WebformLazyBuilder.php
&lt;?php

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class WebformLazyBuilder implements RenderCallbackInterface {

  public static function buildWebform($webform) {
    return  [
      'webform' =&gt; [
        '#type' =&gt; 'webform',
        '#webform' =&gt; $webform,
      ],
    ];
  }

}

Then you can put the lazy builder in a template preprocess hook:
$variables['contact_form'] =  [
  '#lazy_builder' =&gt; ['\Drupal\mymodule\WebformLazyBuilder::buildWebform', ['contact']],
  '#create_placeholder' =&gt; TRUE,
];

Blocks are placed in a lazy builder by default, see BlockViewBuilder::viewMultiple.