Replies: 3 comments 6 replies
-
Otherwise, something like conditional classes but for attributes would be nice: <div class="some-classes"
@attributes([
'x-data' => [ true, "{alpine: 'credit'}" ]
])
>
do something
</div> |
Beta Was this translation helpful? Give feedback.
-
I realized that my request is not that easy to implement. What do you think about adding a tag similar to Here an example: <x-post class="some-classes">
<x-dynamic-attributes :if="$variable == 'use feature 1'" x-data="{alpine: 'credit'}" @click="alert('feature 1 is active')" />
<x-dynamic-attributes :if="$variable == 'use feature 2'" x-data="{alpine: 'credit'}" @click="alert('feature 2 is active')" />
do something
</x-post> Idea behind this: |
Beta Was this translation helpful? Give feedback.
-
Other solution to this by adding the following to method __toString of Illuminate\View\ComponentAttributeBag if ($key === 'x-dynamic-attributes') {
if (!is_array($value)) continue;
$string .= new self(array_map(fn($v) => str_replace('"', "'", $v), $value));
continue;
} Here the full method with this change: /**
* Implode the attributes into a single HTML ready string.
*
* @return string
*/
public function __toString()
{
$string = '';
foreach ($this->attributes as $key => $value) {
if ($value === false || is_null($value)) {
continue;
}
if ($value === true) {
// Exception for Alpine...
$value = $key === 'x-data' ? '' : $key;
}
// Support for dynamic attributes
if ($key === 'x-dynamic-attributes') {
if (!is_array($value)) continue;
$string .= new self(array_map(fn($v) => str_replace('"', "'", $v), $value));
continue;
}
$string .= ' '.$key.'="'.str_replace('"', '\\"', trim($value)).'"';
}
return trim($string);
} Here the example what this does: @php($attributesFeatureA = [
'x-data' => '{alpine: "credit"}',
'@click' => 'alert("feature A is active")',
':comments' => $comments
])
@php($attributesFeatureB = [
'x-data' => '{alpine: "credit"}',
'@click' => 'alert("feature B is active")',
])
<x-post class="some-classes" :x-dynamic-attributes="$feature === 'featureA' ? $attributesFeatureA : $attributesFeatureB">
do something
</x-post> This was tested and works fine. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I am not sure if this is a bug or feature request.
In blade such a syntax ist possible:
However doing the same with a blade component is not possible and results in an syntax error, unexpected token "endif"
It would be nice if something like this would be possible.
I know that something like this works
However if there are a couple attributes there are a lot of if clauses to check...
What do you think?
Cheers
Beta Was this translation helpful? Give feedback.
All reactions