0

For my blog, I want to be able to add css-classes to html-tags when I retrieve them from the DB.

For example, I have in the following in my DB, in a column called body:

<p>
    SO is great
</p>

Then I output it in the View, with sth like this:

{{ blogpost.body }}

But what I actually want to have is this:

<p class="class1 class2 class3">
    SO is great
</p>

How can I do this?

I can only think of using JS and adding the classes but I don't like this idea.

Is there maybe a way to pre-format it and save it ready in the DB? Or is this a bad practice?

Any suggestions are welcome.

6
  • Why you dont like the JS option? Commented Dec 15, 2016 at 14:40
  • p tags arrives like a string? Commented Dec 15, 2016 at 14:41
  • it seems to me that you are already using html in your database so using classes in your DB is not going to harm anything. In fact thats how a lot of custom Wordpress, and php plugins work. Commented Dec 15, 2016 at 14:42
  • @fuzzybaird OK. How should I go about it? Would you like to create an answer about this? Commented Dec 15, 2016 at 14:46
  • @JuanCarlosOropeza It would slow down the loading a bit. Also I would like to find a cleaner solution (at least cleaner in my opinion) but if you think this is the correct way to go, please feel free to create an answer explaining this and I would be happy to test it out. Commented Dec 15, 2016 at 14:47

2 Answers 2

1

So instead of

 SELECT body

can you try:

SELECT REPLACE (body, '<p>', '<p class="class1 class2 class3">') as body

OR UPDATE in your db

UPDATE yourTable
SET body = REPLACE (body, '<p>', '<p class="class1 class2 class3">')
WHERE body LIKE '<p>%'
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer. My objection is that such a query would be unreadable (imagine doing this for every html-element). I think a better option would be to modify the body before inserting it into the DB.
Check update version, of course you have to expand it. But you can make it a function
0

Can you put it in a container?

<div class="{{ blogpost.tags }}">
    {{ blogpost.body }}
</div>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.