A good solution here would be to fetch the block via AJAX. Mage2.tv has an excellent video guide on how to do this. I would definitely recommend watching the full video tutorial from Mage2tv, it will deal with this topic in depth.
As already noted, adding cacheable="false"
to any block on the page will prevent the entire page from being cached by the full page cache, so this isn't a good solution if you want your page to be cached.
So hole punching (as this is called) via AJAX can go like this:
- Create your module, add a new JS file. For example 'your-ajax-call.js'. So the location of the file will be:
app/code/Vendor/YourModule/view/frontend/web/js/your-ajax-call.js
.
Example content:
define(['jquery'], function ($) {
'use strict';
return function (config, element) {
const url = '/fetch/content/from/url';
$.get({
url: url,
cache: false,
success: function (result) {
element.innerHTML = result;
}
})
}
})
Here we will fetch the dynamic content that's available on the url /fetch/content/from/url
. You will need to create a controller that provides the needed content yourself.
- Then in your PHTML, call your new JS file via
data-mage-init
:
<div data-mage-init='{"Vendor_YourModuleName/js/your-ajax-call": {}}'>
<!-- The result of the AJAX call will be added here -->
<div class="your-class">
<span><?= __('Placeholder text') ?></span>
</div>
</div>
The content from /fetch/content/from/url
will be inserted into the div via AJAX after the page load event and you have essentially 'bypassed' the full page cache for this block.