Hi,
I am, again, stuck at something while working on custom blocks and I couldn’t find any solution yet.
In my custom block is a blocks
field, which I want a preview of in the panel. I know how to output content from different fields, but now I’m having some trouble with conditional rendering.
The blocks
field in my "sectiontext" block
uses a text block and a heading block. They both have the field “text” and I can output all the contents in the preview like this:
sectiontext: {
template: `
<div>
<div v-for="item in content.blocks">
<p v-html="item.content.text"></p>
</div>
</div>
`
},
fields:
blocks:
type: blocks
label: Inhalt
fieldsets:
- heading
- text
My problem is that everything is wrapped in <p>
tags. I want my headings wrapped in h2's
etc.
The headings have a select
field to select the level (H2, H3, etc.).
How can I check in my loop if the "level" select field
exists and change the corresponding wrapping tags to be a heading?
Or is it possible to check if my item in the loop is a specific block type and output different HTML?
You probably need a computed property here. For example in a video block i did this…
panel.plugin("hashandsalt/localvideo", {
blocks: {
localvideo: {
computed: {
video() {
return this.content.vidfile.length === 0 ? false : this.content.vidfile[0].url;
}
},
template: `
<div @click="open">
<video v-if="video" autoplay muted loop>
<source :src="video" type="video/mp4">
<p>Your Browser does not support video<p>
</video>
<div v-else>No video selected yet</div>
<div>
`
}
}
});
This shows the preview if the video feild has a value. You should be able to use the same principle to set the heading. You can put the defualt heading level in the else, the switch between the others.
I think I know how it’s done, but for that I need to access a field and I can’t get it to work.
computed: {
heading() {
if (this.content.blocks) {
return true;
}
}
},
^ This returns true
because my blocks
field exists. But I want to check if a block in this blocks
field contains the field “level”. So I’m looking for something like this to access the field:
computed: {
heading() {
if (this.content.blocks.level) {
return true;
}
}
},
Or something like this:
computed: {
heading() {
let blocks = this.content.blocks;
blocks.forEach(block => {
if (block.level) {
return true;
}
});
},
},
Is this possible? Thanks!
I managed to figure it out.
Using computed values did not work out for me so instead I went with this solution:
template: `
<div>
<div v-for="item in content.blocks">
<div v-if="item.content.level === 'h2'">
<h2>{{ item.content.text }}</h2>
</div>
<div v-else v-html="item.content.text"></div>
</div>
</div>
`
I’ll have to make an if-statement for each heading level, but it works for now.
Edit: I just found out how to check for a specific block type:
<div v-for="item in content.blocks">
<div v-if="item.type === 'yourblockname' ">
<h2>{{ item.content.yourfield }}</h2>
</div>
</div>