thkm
February 26, 2019, 6:40pm
1
Hey, I’m building a website with two writing systems. To have proper typesetting, I’d need to target specific parts of the text and apply a class to it.
This is my paragraph (customtag: this is the text I want to target)...
The desired output:
<p>...<span class="customtag">...</span></p>
I tried to follow this without success, any ideas on how to do it in K3?
Thanks
texnixe
February 26, 2019, 6:56pm
2
Could you post your code, please?
thkm
February 26, 2019, 7:14pm
3
I’m using this snippet from the doc:
/site/plugins/custom/index.php
Kirby::plugin('custom', [
'tags' => [
'custom' => [
'attr' => [
'class'
],
'html' => function($tag) {
return '<span class="' . $tag->class . '"></span>';
}
]
]
]);
texnixe
February 26, 2019, 7:39pm
4
Two issues:
Your plugin doesn’t have a name and it’s missing the text value:
<?php
Kirby::plugin('yourname/customtag', [
'tags' => [
'custom' => [
'attr' => [
'class'
],
'html' => function($tag) {
return '<span class="' . $tag->class . '">' . $tag->value() .'</span>';
}
]
]
]);
Once fixed, it should work. Note that you have named the tag custom
, so to use it in your text:
(custom: some text class: myclass)
thkm
February 26, 2019, 8:09pm
5
Thank you @texnixe . Is there a way to define the class directly inside the plugin and not in the markdown? I’ll probably need to repeat this a lot.
texnixe
February 26, 2019, 8:11pm
6
If you want to set a fixed class, yes; or you can set a default in case the attribute is empty.
thkm
February 27, 2019, 1:01pm
7
How would you set a default class if the attribute is empty in this case?
texnixe
February 27, 2019, 1:08pm
8
'html' => function($tag) {
$class = !empty($tag->class)? $tag->class : "default-class";
return '<span class="' . $class . '">' . $tag->value() .'</span>';
}
Thanks to PHP 7 this can even be cleaner:
$class = $tag->class ?? 'default-class';
texnixe
February 27, 2019, 3:07pm
11
Yes, but only if the class attribute in not set at all, not if it is set but empty. That’s why I went for the more elaborate way.
You are right. Mine only works if the class attribute is not set or null.