How to display a string with HTML code ?
Hello,
In my Laravel model, I generate a string like this one saved in a variable.
Mr Henry<br/>Miss Trebble
I want to display this string with VueJS like I could do it with Laravel using {!! ... !!}.
The documentation shows I have to use v-html, but it doesn't work.
Do you have any idea ?
Or perhaps another way to add a new line within a string ?
Thanks.
V
No it's not the solution.
I do not want to display <br/> on the screen, I need that <br/> generates a new line on the screen.
v-html should work; can you share the relevant code?
I have tried both.
<span>
{{ course.trainers_string }}
</span>
<span v-html="course.trainers_string">
</span>
And here is the code that generates the string.
public function getTrainersStringAttribute()
{
$string = '';
$i = 0;
$trainers = $this->trainers;
while ($i < $trainers->count()) {
$string = $string.$trainers[$i]->fullname_short;
if ($i < $trainers->count()) {
$string = $string.'<br/>';
}
$i = $i + 1;
}
$string = Str::of($string)->trim('<br/>');
return $string;
}
The Vue template should work using:
<span v-html="course.trainers_string"></span>
While the Accessor can actually be simplified:
public function getTrainersStringAttribute()
{
return $this->trainers->map->fullname_short->implode('<br />');
}
Thank you ... ok for the accessor ... not ok for v-html ... it doesn't work. Do you have any idea why it could not work ?
What do you see rendered wherever you are using v-html?
An alternative approach would be to get trainers' names as an array in JSON:
public function getTrainersNamesAttribute()
{
return $this->trainers->map->fullname_short;
}
And in Vue, iterate:
<span>
<template v-for="name in course.trainer_names">
{{name}} <br />
</template>
</span>
Yes this works fine, I had already done it like this.
But I need to find a solution to display directly from one string.
In fact I work on a calendar the string is sent to the calendar to be displayed at the right date.
But for the moment I will use your alternative ;).
Other question : I see that you are using a template within the span.
I often see that ... why a template and not a simple div ?
A div would be a block-level element, so that would not be appropriate.
template is transparent - it is not rendered in the resulting HTML, but provides an element to iterate with.
Ok that's fine thank you ;).
In fact I work on a calendar the string is sent to the calendar to be displayed at the right date.
I suppose the Calendar is escaping the HTML string again?
I build the entire calendar, because I do not have found any free calendar to do exactly what I need ... so I write my own code to do what I need ;).
And I learn a lot doing a calendar ;).
Or I think you should try {!! $var !!}
@Nihir I don't think that it's possible with VueJS or ?
@vincent15000 Yes, I read the previous comments and tried it but I'm wrong.
Please or to participate in this conversation.