How can I add a tax toggle to my store?
First, install aerocargo/tax-toggler:
composer require aerocargo/tax-toggler
This module adds a tax_state() twig function that returns inc or ex depending on configuration, see here for more information.
Next let's create the layouts/partials/tax-toggle.twig file:
<label class="inline-flex items-center cursor-pointer">
<span class="hidden md:flex text-xs font-medium uppercase text-gray-900 mr-2">
<span class="price--inc">inc VAT</span>
<span class="price--ex">ex VAT</span>
</span>
<input type="checkbox" id="tax-toggler" value class="sr-only peer" {{ tax_state() == "inc" ? "checked" : "" }}>
<span class="relative w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all"></span>
</label>
{% js %}
<script>
(() => {
let state = "{{ tax_state() }}"
function togglePrices(state) {
let date = new Date();
date.setTime(date.getTime() + 2592000000);
document.body.classList.remove(state === 'inc' ? 'prices--ex' : 'prices--inc');
document.body.classList.add(state === 'inc' ? 'prices--inc' : 'prices--ex');
document.cookie = `prices=${state}; path=/; expires=${date.toUTCString()}`;
}
togglePrices(state);
let toggle = document.getElementById('tax-toggler');
toggle.checked = state === 'inc';
toggle.addEventListener('change', () => {
togglePrices(toggle.checked ? 'inc' : 'ex');
});
})();
</script>
{% endjs %}
{% css %}
<style>
body.prices--inc .price--inc, body.prices--ex .price--ex { display: initial; }
body.prices--inc .price--ex, body.prices--ex .price--inc { display: none; }
</style>
{% endcss %}
2592000000 is 30 days in milliseconds.
Then let's include this file in our header.twig:
{% include "layouts/partials/tax-toggle.twig" %}
Now we just have to mark any prices we display to use this toggle, for example in product.twig:
{# Before #}
<span class="text-xl">{{ "{{ sale_price.inc }}" }}</span>
{# After #}
<span class="text-xl price--inc">{{ "{{ sale_price.inc }}" }}</span>
<span class="text-xl price--ex">{{ "{{ sale_price.ex }}" }}</span>