Render formatted HTML string on webpage - html

I have a bunch of HTML text that looks like this:
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas.
Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet,
ante. Donec eu libero sit amet quam egestas semper.
<em>Aenean ultricies mi vitae est.</em> Mauris placerat
This is text that a user will post forum, and this formatted string is then stored on a server. I am displaying this text on another page, but would like it to be render as the user formatted it, eg:
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet,
ante. Donec eu libero sit amet quam egestas semper.
Aenean ultricies mi vitae est. Mauris placerat
I have tried using <pre>, <p>, and other tags, but they just print out the raw HTML instead of using the formatting given. I am currently using Angular.JS for my page.
Sample text obtained from http://html-ipsum.com/, "Kitchen Sink" example

You are likely storing the string uuencoded, so it displays the codes shown literally.
I'd double check your raw data store to verify this.
In any case THIS IS NOT A RECOMMENDED WAY TO APPROACH YOUR CODE. You are basically inviting a malicious user to potentially inject malicious code into the your other users.
When allowing users to input any html, it is best to only allow a small subset of tags (and a small subset of attributes), and even then it is very hard to get right.
See Cross-Site Scripting (XSS) Tutorial for more.

It sounds like, at some point during the process of storing your HTML, you have escaped the HTML entities (i.e. converted < to <, that sort of thing).
I don't know what language you're working in, but it's possible to unescape HTML characters in pretty much any language. Here's an answer about doing it in JavaScript. The html_entity_decode() method will do the trick in PHP. For whatever language you're working in, just do research on "unescape html entities" in that language.
Warning: since you are unescaping HTML, there's the risk that the user might have written something naughty (i.e. like a <script> tag with some malicious JS code). Make sure you're cleaning out any nasty HTML somewhere along the line.

Related

Is it possible to create a variable text string in HTML?

I have a document where there's a component name that's repeated hundreds of times. I'm trying to make this document into a template where the component name will change from report to report. Instead of having hundreds of iterations of "Example123" in plain text, I'd like to define a variable text string, for example "&ComponentName;" and use that throughout the template so that any change to that variable changes each instance of the component name. Thereby, creating a situation where anyone can create a new document for different components with one change instead of hundreds. Is something like that possible when just using HTML?
I've tried looking up every element in HTML in w3 schools to see if there's something like this, but to no avail. I've also tried searching stack overflow for this, but I think I might be using the wrong terminology and I'm not sure how else to describe what I'm looking for. When I think of "variable" I'm thinking of "X" which can be defined by the user, but when I look up "variable text in html" I tend to get results about <var> which doesn't help in this use case.
I tried to use
<script>
const string = "The revolution will not be televised.";
console.log(string);
</script>
to see if the text string will appear in output, but nothing appeared and I'm unfamiliar with Javascript.
Use some plachoder text inside your html, and then replace all the instances of that text with your component name, in javascript:
const placeholder = '#CMPNT#'
const componentName = 'MY COMPONENT NAME'
document.querySelector('.container').innerHTML = document.querySelector('.container').innerHTML.replaceAll(placeholder, componentName)
<div class="container">
<p>Lorem #CMPNT# dolor sit amet, consectetur adipiscing
elit. Vivamus ac scelerisque augue. Donec eu mattis libero.
Quisque gravida sit amet tellus id #CMPNT#. Orci varius
natoque penatibus et magnis dis parturient montes,
nascetur ridiculus mus. Suspendisse #CMPNT# et magna vel
congue. In non maximus diam. Suspendisse tristique est
vitae nibh sollicitudin varius. Integer at dolor vitae felis
placerat fringilla eu sit amet ipsum. #CMPNT# euismod ipsum
eget neque rhoncus sodales. Cras velit dui, tempus at pulvinar
eget, varius sed #CMPNT#. Donec egestas, erat nec luctus
suscipit, libero quam maximus mauris, id sagittis ligula
quam condimentum lacus.</p>
</div>

I am trying to wrap text around a centered image in CSS separating this into two columns. Has anyone been able to find responsive solution for this? [duplicate]

How to wrap a text around a centered (round) image like this:
I tried this jsfiddle but the text goes behind the image and does not flow around it.
#circle {
float:positioned;
position: absolute;
top:10%;
left: 40%;
wrap-shape: circle(50%, 50%, 120px);
wrap-margin: 10px;
}
<div id="circle"><img src="http://www.guitare-rabuffetti.fr/test/circle.png"/></div>
<div>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam cursus. Morbi ut mi. Nullam enim leo, egestas id, condimentum at, laoreet mattis, massa. Sed eleifend nonummy diam. Praesent mauris ante, elementum et, bibendum at, posuere sit amet, nibh. Duis tincidunt lectus quis dui viverra vestibulum. Suspendisse vulputate aliquam dui. Nulla elementum dui ut augue. Aliquam vehicula mi at mauris. Maecenas placerat, nisl at consequat rhoncus, sem nunc gravida justo, quis eleifend arcu velit quis lacus. Morbi magna magna, tincidunt a, mattis non, imperdiet vitae, tellus. Sed odio est, auctor ac, sollicitudin in, consequat vitae, orci. Fusce id felis. Vivamus sollicitudin metus eget eros.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In posuere felis nec tortor. Pellentesque faucibus. Ut accumsan ultricies elit. Maecenas at justo id velit placerat molestie. Donec dictum lectus non odio. Cras a ante vitae enim iaculis aliquam. Mauris nunc quam, venenatis nec, euismod sit amet, egestas placerat, est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras id elit. Integer quis urna. Ut ante enim, dapibus malesuada, fringilla eu, condimentum quis, tellus. Aenean porttitor eros vel dolor. Donec convallis pede venenatis nibh. Duis quam. Nam eget lacus. Aliquam erat volutpat. Quisque dignissim congue leo.
Mauris vel lacus vitae felis vestibulum volutpat. Etiam est nunc, venenatis in, tristique eu, imperdiet ac, nisl. Cum sociis natoque penatibus et
</div>
As already noted, shape wrapping currently only works for floated elements, so this exact situation isn't do-able with CSS only, because only wrapping on one side of a shape is permitted (expected). Once the CSS Shapes 2 and/or CSS Exclusions specs) are adopted, we will be able to do this with not only shapes but also image transparency.
I ran into this same problem while trying to figure out how shapes and CSS columns interact (spoiler: decent, but not organically). The problem seems to be that the layout algorithm looks for the farthest edge (ignoring the possiblity of multiple sides), then starts content layout from that coordinate. For elements in the middle, this means you get text only on one side. For CSS columns (which is how I figured this out), the layout again starts from the farthest edge, but then continues straight down instead of wrapping to the shape on each line (see fiddle), so protrusions on shapes (like a star polygon) can actually force wrapping content to end up below the entire shape instead of squished to one side or flowing down into the protrusion.
(note there are 3 sets of 2 columns on 2nd example)
However, there are a couple options that may work for similar situations. I have adapted the following from the other answers/comments, but had to make several changes to get them working (and several of the CSS attributes were experimental and are no longer valid), so I felt this was better as a new answer than as edits/comments:
Wrap one side
Use shape-outside on a left floated div to create a wrapping circle, then use margin-left to push it away from the left side. I added a circle inside the div for illustration (your image URL is 404), but had to tweak the location as Chrome did not calculate its position the way one would expect once margins were added.
http://jsfiddle.net/brichins/50h20kxa/1/
Columns and mirrored wrapping elements
If columns are acceptable, manually (see above CSS column discussion) creating 2 containers for columns and placing a shaped element on the side of each gives the following:
http://jsfiddle.net/brichins/gvhpfccu/
The disadvantage here is columns where you may have wanted a single block (not necessarily bad for readability), as well has having to compute an appropriate split for your content.
Reading
Intro and walkthrough on HTML5 Rocks: https://www.html5rocks.com/en/tutorials/shapes/getting-started/
References the amazing Alice in Wonderland example from 2013. It appears to not function completely anymore, but the entire talk is still interesting
Creating Non-Rectangular Layouts With CSS Shapes: https://sarasoueidan.com/blog/css-shapes/
CSS Tricks article: https://css-tricks.com/almanac/properties/s/shape-outside/
D3plus workaround plugin (for similar SVG solutions): https://d3plus.org/examples/utilities/a39f0c3fc52804ee859a/
Question resolved :
Actual situation :
The CSS shape works for float, so it's not for centered images now. This property works only for Chrome and Opera at the moment.
Maybe there will be a solution for non float elements in the future. Look at this W3C editor's draft : http://www.interoperabilitybridges.com/css3-floats/OriginalSubmition.html
A hand made CSS solution :
Basically, there are 2 columns (like in newspapers). The text begins in the left column and goes down. The text continues on the top of the right column and goes down. The columns are a bit higher than the image. The left column has a half invisible circle as well as the right column - on the position of the centered image. The two half circles are build by multiple boxes of different length, they are invisible. (The hight of the boxes is the height of the font.) The text must be justified. The text is now flowing around the half circles in each column. The image will be positioned over the 2 invisible half circles.
Another, not very technical solution is to use Libre Office and Inkscape to produce an SVG file.
Import the picture into Libre Office - wrap the text around the image - save as PDF - open Inkscape - save as SVG - import the SVG in your Webpage - done.
Thanks everybody for helping me and for your inputs !
I don't think it's possible since it relies on float and you can't float to the middle/center of the page.
Here's what I came up with:
[old fiddle]/5Lxc444p/8/
If you put the width style on the actual circle it works better than on a parent div.
Also, here's a good writeup on css shapes: http://www.html5rocks.com/en/tutorials/shapes/getting-started/
EDIT:
Here's an updated fiddle for the 2 column layout with absolute positioned circle.
http://jsfiddle.net/5Lxc444p/11/

Global RegEx search and replace to fix HTML in an XML export file?

I have a fairly large WordPress .XML export file from a blog that I am going to migrate to Drupal. One glaring issue with the export file is that it's missing <p> tags for any paragraph breaks. However, the tags are present on the actual site.
From what I can see from the raw text in the XML file, there are multiple line breaks between paragraphs where there should have been a single <p> tag. I was hoping to globally add in a <p> tag where there's a line break and a capital letter using RegEx but I don't have a working knowledge of how that works. A sample XML tag in the export file that contains the text in question is:
<content:encoded><![CDATA[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur gravida risus at sem interdum iaculis. Curabitur eget est tellus, quis viverra arcu.
Cras posuere turpis imperdiet odio aliquet sollicitudin. Maecenas et neque eget quam fringilla tempor. Vivamus sodales vulputate consectetur.
Sed ullamcorper elementum est, at dapibus orci fermentum vitae. Vivamus nisi turpis, pretium sed tincidunt et, dapibus at eros. Quisque neque magna, posuere eget eleifend ut.
As you can see from the above, there are multiple line breaks in between what should be paragraphs. I was thinking of the line break / capital letter combo for the RegEx so as to only put in one <p> tag and also target specifically the <content:encoded> XML tag so that I don't add tags elsewhere in the XML file. One other issue to make things more complicated is that some paragraphs already have <p> tags where the editor added in a custom class like <p class="myclass">.
This issue was discussed on StackOverflow somewhere before. Problem is, that Wordpress doesn't store the p tags in its database (if you use its WYSIWYG editor), these tags are created upon rendering by wpautop() function (instead of breaks). So I edited the export.php file (running WP 3.4.1) and added the function there. You can see the result on Pastebin (changes are on lines 375 and 376).
<content:encoded><?php echo wxr_cdata( apply_filters( 'the_content_export', wpautop( $post->post_content ) ) ); ?></content:encoded>
<excerpt:encoded><?php echo wxr_cdata( apply_filters( 'the_excerpt_export', wpautop( $post->post_excerpt ) ) ); ?></excerpt:encoded>
You can copy and paste the whole code in file [root]/wp-admin/icludes/export.php and run the export again. Don't forget to backup the file before - I don't guarantee it will work other versions, but you can get the idea how to edit the export.

Replace single words/lines with text from multiple inputs

What would be the best method for replacing variables/words/lines of text in a larger "paragraph" of code?
Example:
Lorem ipsum dolor $SIT amet, consectetur adipiscing elit. Aliquam condimentum dolor ut est faucibus dapibus. Donec molestie dictum nisi, eu euismod $SAPIEN gravida in. Aliquam dictum, tellus eu facilisis laoreet, sapien nunc placerat turpis, eu pretium augue eros vel lectus. Quisque condimentum lorem $EROS, vel pharetra tortor.
I want to be able to enter text in a textbox/prompt to replace the "Variables" $SIT, $SAPIEN, $EROS with actual values automatically.
I trust I've made myself obscure? :P
I'm n00b at any sort of coding. I only know some basic HTML, PHP, and Java. But please give me a clear solution with an example or link or more help.
Thanks so much!
You must utilize JavaScript if you want to do it client-side, and any of the server-side ones [PHP, Python, Ruby] if you want to do it that way. In all of these languages there are equivalents of "string replace" functions, that'll take list of strings to search, list of strings to replace and subject that they will be working on. Solution for JS and PHP:
http://php.net/manual/en/function.str-replace.php
http://www.w3schools.com/jsref/jsref_replace.asp
The way that you'll do it is up to you.

How would you abbriviate XHTML to an arbitrary number of words?

How would you programmacially abbreviate XHTML to an arbitrary number of words without leaving unclosed or corrupted tags?
i.e.
<p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget,
hendrerit, <em>justo</em>.
</p>
Abbreviated to 25 words would be:
<p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue...</span>
</p>
Recurse through the DOM tree, keeping a word count variable up to date. When the word count exceeds your maximum word count, insert "..." and remove all following siblings of the current node, then, as you go back up through the recursion, remove all the following siblings of each of its ancestors.
You need to think of the XHTML as a hierarchy of elements and treat it as such. This is basically the way XML is meant to be treated. Then just go through the hierarchy recursively, adding the number of words together as you go. When you hit your limit throw everything else away.
I work mainly in PHP, and I would use the DOMDocument class in PHP to help me do this, you need to find something like that in your chosen language.
To make things clearer, here is the hierarchy for your sample:
- p
- Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
- p
- Proin semper, orci at mattis blandit, augue justo blandit nulla.
- span
- Quisque ante congue justo
- , ultrices aliquet, mattis eget, hendrerit,
- em
- justo
- .
You hit the 25 word limit inside the span element, so you remove all remaining text within the span and add the ellipsis. All other child elements (both text and tags) can be discarded, and all subsequent elements can be discarded.
This should always leave you with valid markup as far as I can see, because you are treating it as a hierarchy and not just plain text, all closing tags that are required will still be there.
Of course if the XHTML you are dealing with is invalid to begin with, don't expect the output to be valid.
Sorry for the poor hierarchy example, couldn't work out how to nest lists.