Meteor {{#markdown}} - html

I am making a forum with markdown support.
I've been using meteor's markdown parser {{#markdown}} and have found something disturbing that I can't seem to figure out.
I am using {{#markdown}}{{content}}{{/markdown}} to render the content inserted into database.
The disturbing thing, for example, if someone writes up html without inserting it into the code block in the content...
example
<div class = "col-md-12">
Content Here
</div>
This will render as a column. They could also make buttons and etc through writing the HTML for it.
How to disable this behaviour so that when HTML is written it will not render into HTML but just simply show it as text?

You can write global helper, which will strip all html tags:
function stripHTML(string){
s = string.replace(/(<([^>]+)>)/ig, '');
return s;
}
Template.registerHelper('stripHTML', stripHTML)
Usage :
{{#markdown}}{{stripHTML content}}{{/markdown}}
Test it in console:
stripHTML("<div>Inside dive</div> Text outside")

Related

Getting a HTML template as a HTML string

consider that I have several HTML templates and they have custom HTML tags. For ex: c-icon, c-text, c-button etc.
For some usecase(Display other content along with innerHTML), I need to access c-icon tag HTML inside c-text and append it to some text so that I can render it with some other html text. In future, I may have another component called c-badge and even I want to refer and render.
Could you please provide any suggestions for achieving the same?

How to Create an HTML Template?

Problem
I have a collection of images with linked captions on a page. I want them each to have identical HTML.
Typically, i copy and paste the HTML over and over for each item. The problem is, if i want to tweak the HTML, i have to do it for all of them. It's time-consuming, and there's risk of mistakes.
Quick and Dirty Templating
I'd like to write just one copy of the HTML, list the content items as plain text, and on page-render the HTML would get automatically repeated for each content-item.
HTML
<p><img src=IMAGE-URL>
<br>
<a target='_blank' href=LINK-URL>CAPTION</a></p>
Content List
IMAGE-URL, LINK-URL, CAPTION
/data/khang.jpg, https://khangssite.com, Khang Le
/data/sam.jpg, https://samssite.com, Sam Smith
/data/joy.jpg, https://joyssite.com, Joy Jones
/data/sue.jpg, https://suessite.com, Sue Sneed
/data/dog.jpg, https://dogssite.com, Brown Dog
/data/cat.jpg, https://catssite.com, Black Cat
Single Item
Ideally, i could put the plain-text content for a single item anywhere on a page, with some kind of identifier to indicate which HTML template to use (similar to classes with CSS).
TEMPLATE=MyTemplate1, IMAGE-URL=khang.jpg, LINK-URL=https://khangssite.com, CAPTION=Khang Le
Implementation
Templating systems are widely used, like Django and Smarty on the server side, and Mustache on the client side. This question seeks a simple, single-file template solution, without using external libs.
I want to achieve this without a framework, library, etc. I'd like to put the HTML and content-list in the same .html file.
Definitely no database. It should be quick and simple to set it up within a page, without installing or configuring additional services.
Ideally, i'd like to do this without javascript, but that's not a strict requirement. If there's javascript, it should be ignorant of the fieldnames. Ideally, very short and simple. No jquery please.
you mean Template literals (Template strings) ?
const arrData =
[ { img: '/data/khang.jpg', link: 'https://khangssite.com', txt: 'Khang Le' }
, { img: '/data/sam.jpg', link: 'https://samssite.com', txt: 'Sam Smith' }
, { img: '/data/joy.jpg', link: 'https://joyssite.com', txt: 'Joy Jones' }
, { img: '/data/sue.jpg', link: 'https://suessite.com', txt: 'Sue Sneed' }
, { img: '/data/dog.jpg', link: 'https://dogssite.com', txt: 'Brown Dog' }
, { img: '/data/cat.jpg', link: 'https://catssite.com', txt: 'Black Cat' }
]
const myObj = document.querySelector('#my-div')
arrData.forEach(({ img, link, txt }) =>
{
myObj.innerHTML += `
<p>
<img src="${img}">
<br>
<a target='_blank' href="${link}">${txt}</a>
</p>`
});
<div id="my-div"></div>
This answer is a complete solution. It's exciting to edit the HTML template in codepen and watch the layout of each copy change in real time -- similar to the experience of editing a CSS class and watching the live changes.
Here's the code, followed by explanation.
HTML
<span id="template-container"></span>
<div hidden id="template-data">
IMG,, LINK,, CAPTION
https://www.referenseo.com/wp-content/uploads/2019/03/image-attractive.jpg,, khangssite.com,, Khang Le
https://i.redd.it/jeuusd992wd41.jpg,, suessite.com,, Sue Sneed
https://picsum.photos/536/354,, catssite.com,, Black Cat
</div>
<template id="art-template">
<span class="art-item">
<p>
<a href="${LINK}" target="_blank">
<img src="${IMG}" alt="" />
<br>
${CAPTION}
</a>
</p>
</span>
</template>
Javascript
window.onload = function LoadTemplate() {
// get template data.
let sRawData = document.querySelector("#template-data").innerHTML.trim();
// load header and data into arrays
const headersEnd = sRawData.indexOf("\n");
const headers = sRawData.slice(0, headersEnd).split(",,");
const aRows = sRawData.slice(headersEnd).trim().split("\n");
const data = aRows.map((element) => {
return element.split(",,");
});
// grab template and container
const templateHtml = document.querySelector("template").innerHTML;
const container = document.querySelector("#template-container");
// make html for each record
data.forEach((row) => {
let workingCopy = templateHtml;
// load current record into template
headers.forEach((header, column) => {
let value = row[column].trim();
let placeholder = `\$\{${header.trim()}\}`;
workingCopy = workingCopy.replaceAll(placeholder, value);
});
// append template to page, and loop to next record
container.innerHTML += workingCopy;
});
};
New version on github:
https://github.com/johnaweiss/HTML-Micro-Templating
Requirement
As specified in the question, this solution is intended to optimize the coding experience on the HTML side. That's the whole point of any web templating. Therefore, the JS has to work a little harder to make life easier for the HTML programmer.
The question seeks a reusable solution. Therefore, JS should be ignorant of the template, fields, and data-list. So unlike #MisterJojo's answer, the template and all data are in my HTML, not javascript. The JS code is generic.
Design
My solution is based on the <template> tag, which is intended for precisely this usage. It has various advantages, like the template isn't displayed, processed, or validated by the browser, so it has less impact on performance. Programmer doesn't have to write an explicit display:none style.
https://news.ycombinator.com/item?id=33089975
However, <template> tags are normally only intended for loading content into the layout. That's inadequate. This tool allows template variables anywhere in the HTML, including inside the tags (eg attributes like <img src).
HTML
My HTML has three blocks:
template: The HTML coder develops their desired display-structure of the output, in real HTML (not plain text). Uses <template>
data: The list of records each of which should be rendered using the same template. Uses <span> with a HIDDEN attribute.
container: The place to display all the output blocks. Uses <span>.
Template
My sample template includes 3 placeholders for data:
${LINK}
${IMG}
${CAPTION}
But of course you can use any placeholders, any number of them. I use string-literal delimiting-style (although i'm not actually using them as string-literals -- i just borrowed the delimiter style.)
Data Element
The question specifies data should be stored in HTML. It should require minimal keystrokes.
I didn't want to redundantly retype the fieldnames on every row. I didn't use slotting, JSO, Jason, or XML syntax, because those are all verbose.
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots
It's a simple delimited list. I eliminated all braces, brackets, equals, parens, colons etc.
I put the fieldname-headers only on the first row. The headers are a visual aid for the HTML developer, and a key for Javascript to know the fieldnames and order.
Record Delimiter: End-of-line
Field Delimiter: Double-commas. Seems safe, and they're easy to type. I don't expect to see double-commas in any actual data. Beware, the developer must enter a space for any empty cells, to prevent unintended double-commas. The programmer can easily use a different delimiter if they prefer, as long as they update the Javascript. You can use single-commas if you're sure there will be no embedded commas within a cell.
The data block is hidden using the hidden attribute. No CSS needed.
It's a span to ensure it takes up no room on the page.
JAVASCRIPT
Data
The data is processed by Javascript with two split statements, first on newline delimiter, then on the double-comma delimiter. That puts the whole thing into a 2D array. My JS uses trims to get rid of extra whitespace as needed.
Place-holder Substitution
Handling multiple entries requires plugging each entry into the template.
i went with simple string-replacement instead of string literals.
Multiple Templates
New version which supports multiple templates, and ability to use same template in multiple locations on same page.
https://github.com/johnaweiss/HTML-Micro-Templating
Future
Inspired by #MisterJojo, an earlier version of my solution used template literals to do the substitution. However, that was a bit more complicated and verbose, and seemed to require use of eval. So i switched to .replaceAll. Yet template-literals seems like a more appropriate method for templates, so maybe i'll revisit that.
A future version may adapt to whatever custom field-delimiter the HTML developer uses for the data block.
The dollar-curly delimiter for placeholders is a bit awkward to type. So i'm interested in finding a less awkward non-alpha delimiter that won't conflict with HTML. Considering double-brackets or braces [[NAME]]
Maybe there are simpler ways to pull the data-table into JS.
I've read components work well with <template>, but i didn't go there.
Imo, the JS committee should develop a variable-placeholder feature for <template> tags, and natively accommodate storing the data in HTML. It would be great if something like this solution was part of the rendering engine.

Escaped HTML markup being rendered in dangerouslySetInnerHTML?

I have a Gatsby + WP API blog setup (with Markdown enabled) and it's working great, except when I'm trying to display HTML markup as code snippets. I'm using escape characters (see below), but for some reason the HTML inside the <code>/<pre> tags is rendering as actual HTML instead of displaying as an HTML code snippet.
I understand that's what dangerouslySetInnerHTML is there to do, but I didn't think it would if I'm using the escape character <?
Here's the markup inside the WP blog post..
<pre class="language-markup"><code>
<div>
<p>Lorem ipsum...</p>
</div>
</code></pre>
And this is how I'm displaying the entire post content in the react component...
<section className="article-body" itemProp="articleBody"
dangerouslySetInnerHTML={{ __html: this.props.html }}
/>
The <div> and <p> tags rendering as HTML, instead of displayed as a code snippet..
Is there some other way I should be doing this? For the record I also tried this using a 'non-dangerously' method (react-render-html) with the same results.
-- UPDATE: --
I was able to display the HTML as a code snippet by replacing the <code> tag with <xmp>. I know this tag is no longer officially supported, and it's far from elegant, so I think I may try to separate code snippets from the rest of the content as suggested below.
I tried it in CodeSandbox, too - working as expected. If you're sure about data (escaping) received from WP API I affraid it's a Gatsby issue. There must be a place where it's modified (unescaped).
If data will be ok and you don't want to make deep ivestigation there could be workaround. Split article body and treat sections separately - texts and code snippets. The second wrap with code literal with sth like this:
const CodeBlock = (props) => {
return <section className="article-code">
<pre className="language"><code>{`${props.html}`}</code></pre>
</section>
}
Of course remove unused first and last line of original code/snippet block.

How to properly use same text sections across multiple html pages?

I am making help content documentation for an already made software (the kind of which opens in every software when you press F1 or navigate to the Help section in the menu bar). I am using simple html/CSS/js pages to do so.
There is a ton of the same text descriptions of various software properties that appear in more than one page. The idea is to make a single text source file, where all the text descriptions are located and then use some sort of referencing to that specific text section wherever necessary.
Kind of a similar to using a CSS stylesheet to apply styles over all of the pages, only this handles text instead of styles. This way I would be able to change text in only one file and it would apply everywhere it is used.
I ran across the html SSI method, but this only includes the entire html page and not just a specific text section the way I would like to. I would strongly avoid using different file for each text section.
Can anyone please point me into the right direction here?
I think that you can make a JavaScript function that contains the common texts and use this functions in your code whenever you need them, for this the JavaScript that you create should be an external file and you can reference it in every html page you need it.
For example, you can have one function that returns "Hello World" and set this to a "p" element with the id="title". So in every page where you have an element with the id title you can call your JavaScript function to set its text to "Hello World". Use this link to find out more about this topic:
http://www.w3schools.com/js/js_htmldom_html.asp
UPDATE: I did a little test, i created the following JavaScript:
function helloTitle(){
var text = "Hello World!";
document.getElementById("title").innerHTML = text;
}
And referenced it in some HTML pages like this:
<script src="commonText.js" type="text/javascript"></script>
After that i only need to call the function in the element i want it to modify:
<p id="title"><script>helloTitle();</script></p>
This is a solution if you are only using JS, CSS and HTML. There should be other ways to achieve this.
Hope this information could help you!
I figured out how to do it a little more comforatbly on a large scale using the html command https://www.w3schools.com/tags/tag_iframe.asp
in your main html file you do:
<p> <iframe src="Text.html" width="100%" height="300" style="border:1px solid black;"> </p>
and then with some basic html formating insert whatever text u want
<html>
<body>
hmm idk what i should put here. Test
</body>
</html>
there will also be some css formatting needing to be done before it look perfect, but if you want to make multi line blocks I think this is the easiest way to.

Need to render HTML with Play parameters

I have an object that has a title and some text (item.itmTitle and item.itmText) which I am passing to an HTML template using Play's render() method. Within the template (which in this case is called "index.html) I am trying to display the contents of the item object:
.
.
.
<p class="title">${item.itmTitle}</p>
<div id="itemtext">${item.itmText}</div>
.
.
.
My problem is this: the contents of item.itmText are HTML formatted. What I would like is for the contents to be displayed as HTML, but what is happening is that Play is doing all necessary conversions to display the contents as text. In other words, if item.itmText has the following HTML:
<p>This is a paragraph formatted in HTML</p>
The play template converts the source as follows:
& lt;p& gt;This is a paragraph formatted in HTML& lt;/p& gt;
My question is: is there some way to stop this conversion and make the HTML appear on the page as renderable HTML?
Someone please advise.
${item.itmTitle.raw()}
You just need to make sure that these strings are guaranteed to be safe; e.g. if users are submitting the title or text you need to sanitize the content to prevent injection of javascript (or accidental breakage of your container tags).