How to remove HTML tags in Drupal 8 - drupal

$variables['slide_one_description'] = wordwrap(theme_get_setting('slide_one_description','metroman'), 20,"<br>");
In the above, I set the variable for slider description, I just want to apply line break for after some length, but the above code print HTML br tag instead of line break.
Note: description is a dynamic content and I want to solution in Drupal 8.

There used to be functions such as SafeMarkup::checkPlain() that performed this function, but they have been largely deprecated and removed. Most of the time, Twig will do your text sanitization for you, but there are times where you just need an HTML-stripped value in PHP in Drupal.
For example, PHP has a [strip_tags()][1] function that does exactly what the name implies.
Or, for a more Drupal-friendly way, just pass the value through a t() function and use a # replacement to force plain text. Here's an example of how it works:
$value = '<p>Here is a <b>value</b> with HTML.<br>Let's remove it.</p>';
$stripped_value = t('#value', ['#value' => $value]);
This is a trivial example, of course, but you can apply it to other scenarios. Also, this just gets rid of <br> tags, rather than replacing them with line breaks; you'd need a PHP function like the following to replace <br> tags with something else:
function br2nl($string)
{
return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}

Related

How to increase row height in vaadin grid accordingly to data in the cell

I am consuming data from the list and some list may contain multiple line data, so how that can be reflected in the vaadin grid at runtime.
This is the code
public Grid GridBasic() {
grid.removeAllColumns();
grid.addColumn(TopicConsumedDetails::getPartitionNumber).setHeader("PARTITION ");
grid.addColumn(TopicConsumedDetails::getOffset).setHeader("OFFSET");
grid.addColumn(TopicConsumedDetails::getMessage).setHeader("MESSAGE");
grid.setItems(details);
grid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT);
grid.getColumns().forEach( col -> col.setAutoWidth(true));
return grid;
}
This just displays all the data in a single line and it requires scrolling left to right.
Vaadin Version :23.3.1
Use the built-in "wrap cell content" variant: https://vaadin.com/docs/latest/components/grid/#wrap-cell-content
grid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT);
As per the previous answer, I think that using this is the correct approach:
grid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT);
However, you are overriding this setting by calling
grid.getColumns().forEach( col -> col.setAutoWidth(true));
According to the documentation, this automatically sets the column width based on the contents, leading to the right scroll problem.
If you remove this call, you should get the proper wrapping behavior. I was able to reproduce the problem and then see a result like this once I removed the auto width setting:
Alternatively, if you have sensible line breaks in the content you want to wrap, you can do that--but it won't happen automatically, as mentioned by #Rolf in a comment above. That is because the line breaks in the text are basically just whitespace and aren't respected as such by the HTML. So in order to do that, one option is to add an "Html" component column. You can then replace your text's line breaks with <br/> tags, which you could do with a regular expression. It would look like this:
String myColumnText = colText.replaceAll(....); //Some regex to match on your particular line breaks
grid.addComponentColumn(item -> new Html("<p>" + myColumnText +"</p>");
The <p> tags (or some wrapper tags) are required as the Html component requires a wrapper tag.
Note that (1) using this approach means that you won't get the automatic wrapping behavior any more so the line breaks in your source need to be sensible and (2) you have to be certain you trust the incoming content or it is otherwise sanitized, as this kind of rendering-text-as-html opens up some security holes with untrusted content.

SimpleDom Search Via plaintext Text

I am using "PHP Simple HTML DOM Parser" library and looking forward to find elements based on its text value (plaintext)
For example i need to find span element using its value "Red".
<span class="color">Red</span>
I was expecting bellow code to work but seems that it just replaces the value instead of searching it.
$brand = $html->find('span',0)->plaintext='Red';
I read Manual and also i tried to look in library code itself but was not able to find the solution, kindly advise if i am missing something or it is simply not possible to do via Simple Html DOM Parser.
P.S
Kindly note that i am aware of other ways like regex.
Using $html->find('span', 0) will find the (N)th span where in this case n is zero.
Using $html->find('span',0)->plaintext='Red'; will set the plaintext to Red
If you want to find the elements where the text is Red you could use a loop and omit the 0 to find all the spans.
For example, using innertext instead of plaintext:
$spansWithRedText = [];
foreach($html->find('span') as $element) {
if ($element->innertext === "Red") {
$spansWithRedText[] = $element;
}
}

Is there a way to trim newlines out of a twig string?

I'm using objects in my view that I recover from a iCalendar file, these objects have string attributes, named description, and some of these strings contain "\n", and for some multiple times and I can't seem to find a way to trim them out.
I've tried to trim them using the php function in the controller, however they still are there after the function.
Same for the trim function in Twig.
I am maybe using wrong parameters in these functions.
{{ coursCourant.description|split("(")[0]|split(".")[0] }} <BR>
This displays something like "\n\nPromo S4\n" when the expected result is the same thing but without the multiple "\n".
I'm using splits on a ( and on a . because some strings contains them and I don't need to display the parts after those.
trim will only remove trailing and ending whitespaces.
Use str_replace in your controller (recommended)
$content = str_replace("\n", '', $content);
Use replace in your template
{{ foo|replace({"\n":'',}) }}
hence the double quotes to remove an actual newline character

How to represent markdown properly with escaping and line breaks?

I'm currently trying to build a chat app, using the official markdown package as well as underscore's escape function, and my template contains something like this:
<span class="message-content">
{{#markdown}}{{text}}{{/markdown}}
</span>
When I grab the text from the chat input box, I try to escape any HTML and then add in line breaks. safeText is then inserted into the database and displayed in the above template.
rawText = $("#chat-input-textbox").val();
safeText = _.escape(rawText).replace(/(?:\r\n|\r|\n)/g, '\n');
The normal stuff like headings, italics, and bold looks okay. However, there are two major problems:
Code escape issue - With the following input:
<script>alert("test")</script>
```
alert('hello');
```
This is _italics_!
Everything looks fine, except the alert('hello'); has become alert('hello'); instead. The <pre> blocks aren't rendering the escaped characters, which makes sense. But the problem is, the underscore JS escape function escapes everything.
SOLVED: Line break Issue - With the following input:
first
second
third
I get first second third being displayed with no line breaks. I understand this could be a markdown thing. Since I believe you need an empty line between paragraphs to get linebreaks in markdown. But having the above behaviour would be the most ideal, anyone know how to do this?
UPDATE Line break issue has been solved by adding an extra \n to my regex. So now I'm making sure that any line break will be represented with at least two \n characters (i.e. \n\n).
You should check the showdown docs and the wiki article they have on the topic.
The marked npm package, which is used by Telescope removes disallowed-tags. These include <script> of course. As the article I linked to above explains, there's still another problem with this:
<a href='javascript:alert("kidding! Im more the world domination kinda guy. Muhahahah")'>
click me for world peace!
</a>
Which isn't prevented by marked. I'd follow the advice of the author and use a HTML sanitation library. Like OWASP's ESAPI or Caja's html-sanitizer. Both of these project's seem outdated dough. I also found a showdown extension for it called showdown-xss-filter. So my advice is to write your own helper, and use showdown-xss-filter.

Why is wp_editor in Wordpress passing line breaks as "\n" not as "<br>" or "<p>"?

I'm writing a plugin that uses its own database tables (created and managed with dbDelta and wpdb). One of the fields is a rich-text area field. I am using wp_editor to create it. I create the following:
Hit "bold" and type "First Line"
Hit return (to move to next line) and type "Second line"
This appears correctly inside the textarea (it's correct after I type it, it's incorrect when I reload after saving). However, when I save it, it shows in the database as:
ACTUAL RESULTS
<strong>First Line</strong>
Second Line
But it should be:
EXPECTED RESULTS
<strong>First Line</strong><br>Second Line
Why is it doing this? How do I make it pass my code line breaks as HTML line breaks?
I instantiate it like this:
wp_editor( $myContent, "myField", array( "media_buttons" => false, "textarea_rows" => 5, "quicktags" => false ) );
This is default behavior.
p and br tags are not added to the editor. They are used with the visual editor (for display), but when you save or switch to text, they are replaced with regular line breaks.
Single line breaks become a br, double line breaks will start a p.
Linebreak to element conversion is done when the content is displayed, using the_content filter (more specifically, with wpautop).

Resources