1

I have already setup fields for user to input color code (e.g. "#123000") to a content type. Now I need to modify the inline style color / background-color with the given value. I tried to do this in my Custom Text field:

    <div class="box" style="color: {{ color_field }}">
        <h2>{{ title }}</h2>
        <span class="description">{{ body }}</span>
    </div>

But the rendered output would become:

    <div class="box">
        <h2>Dummy</h2>
        <span class="description">Some dummy description...</span>
    </div>

I went as far as creating my own Twig function implementation:

    <div class="box" {{ my_dummy_function(color_field) }}>
        <h2>{{ title }}</h2>
        <span class="description">{{ body }}</span>
    </div>

The function would supposedly output style="color: color_field_value", but the whole attribute would be "eaten" by Drupal's rendering chain. Even adding a | raw filter after that would not change a thing.

    <div class="box">
        <h2>Dummy</h2>
        <span class="description">Some dummy description...</span>
    </div>

In desperate, I modified my dummy Twig function to output hello="world", and the attribute would be rendered normally:

    <div class="box" hello="world">
        <h2>Dummy</h2>
        <span class="description">Some dummy description...</span>
    </div>

But if it output something like hello="color: world":

    <div class="box" hello=" world">
        <h2>Dummy</h2>
        <span class="description">Some dummy description...</span>
    </div>

So it seems there are some keyword-based filtering going on. And I can't seem to have a way to render anything resembling inline CSS. Is there anyway I can achieve my goal?

0

1 Answer 1

1

This is a problem I've encountered numerous times, and personally I've never had any luck outputting inline styles in a Views field that's been rewritten through the UI.

My solution has always been to create a template file that takes responsibility for rendering the view fields, as that does allow you to use inline styles.

In your case, you could have the file in your theme's /templates folder (I have them in a /views subdirectory), with a filename like:

views-view-fields--your-view-name.html.twig

You'd then just need to slightly tweak the markup you already have:

<div class="box" style="color: {{ fields.field_color_field.content }}">
    <h2>{{ fields.title.content }}</h2>
    <span class="description">{{ fields.body.content }}</span>
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.