I want to center my td element when the text is equals to "-". If the text is equals to something else, I want it align at the left.
How can I do that?
<td x-bind:style="$el.textContent == '-' ? { 'text-align': 'left' } : { 'text-align': 'center' }" x-text="format(variable)"></td>
Yes, I could simple replace the $el.textContent by format(variable), but I would like to not call format(variable) twice.
You can use the variable itself at the style binding:
<td x-bind:style="variable !== '' ? { 'text-align': 'left' } : { 'text-align': 'center' }" x-text="format(variable)"></td>
This way the style binding is reactive as well.
If you really want to avoid using variable at the style binding, you can combine x-init with the $nextTick magic to wait until Alpine.js finishes updating the DOM, so you can grab the actual content of the cell and update the cell's style if it's just a dash. However this method is not reactive.
<td x-init="$nextTick(() => {if ($el.textContent == '-') {$el.style['text-align'] = 'center'}})"
x-text="format(variable)">
</td>