EJS rendering HTML - html

I've got a simple blog app on Express and MongoDB, using EJS to render my data.
The problem I have is I want this to be styled like a paragraph:
<div class="show-post__content">
<%= post.body %>
</div>
The content of the post.body is: '<p>Hello there, this is a new post.</p>'
but it's rendering like this:
If the picture doesn't work, it's showing up with the brackets visible, rather than looking like an actual html p tag if that makes any sense...
Does anyone know how to get around this?
Many thanks,
Raph

I've got it:
<div class="show-post__content">
<%- post.body %>
</div>
Is the answer.
Thanks if you had a look!

To be honest, I had the similar issue a week ago
Mission was to disable javascript. I did that with sanitizer.
I sanitized user info before inserting in MongoDB.
So recommend you to do that with sanitize-html striptags.
Those packages are in npm you can download the package.
I hope you will solve the problem.
var striptags = require('striptags');
YourCollectionName.find({}, function (err, obj) {
if (err) {
//handle or throw error
}
// For all the documents, remove html tags and save
obj.forEach(function(ob){
ob.body= striptags(ob.body);
ob.save();
});
});

Related

Redirecting to alternative page if a linked document from <a> not found

I'm looking to see if there is some way to provide an alternative link for a hyperlink to follow if the primary doesn't exist, similar to an image 'alt'. I know 'onerror' exists but it doesnt seem to work for html links. I'd like to avoid JS if possible. If its unavoidable I'm willing to explore its options however.
So in short, if I use:
Link
If it cant find 'TestFile.html', I'd like it to redirect to somewhere else, say TestFile2.html.
<button onclick="onclick()">redirect</button>
<script>
const fs = require('fs')
const path = './TestFile.html'
function onclick() {
try {
if (fs.existsSync(path)) {
//file exists
return res.redirect('/server/TestFile.html');
}
} catch(err) {
//file unknown
return res.redirect('/server/TestFile2.html');
}}
</script>
This should work! But it might not, because I suck at coding and this is a Frankenstein of multiple online sources. Thank You!

why ckeditor content stored in database do not display as html in php

I am working on blog section of a project. I integrated ckeditor and saved data to database. When i display it in php it shows plain text instead of html. I have tried different ways but couldn't resolve the problem. Please some one guide me. thanks.
my function to save data in database
public function store_blog(Request $request){
$fname=null;
if($request->hasFile('image')){
$file=$request->file('image');
$fileName=uniqid().'.'.$file->getClientOriginalExtension();
$file->move(public_path('uploads/blogs/'),$fileName);
$fname=asset('uploads/blogs/'.$fileName);
}
$bbody=$request->blog_body;
$bbody = trim($bbody);
$bbody = stripslashes($bbody);
$bbody = htmlspecialchars($bbody);
Blog::create([
"title"=>$request->title,
"short_description"=>$request->short_desp,
"body"=>$bbody,
"cover_image"=>$fname,
"slug"=>str_replace(" ","_",$request->title),
]);
return redirect()->route('blog_index')->with('success','Blog created successfully');
}
this function saves content successfully. But when i fetch and display in laravel blade view. Ckeditor content displayed all html as plain text/string. How can i force this to render html.
function to fetch blog from database
public function show_Ablog(Request $request,$slug){
$blog=Blog::where('slug',$slug)->first();
return view('website.showAblog',compact('blog'));
}
in my blade view
<div class="col-lg-12 dat">
{{($blog->body)}}
</div>
i have tried all functions like
htmlspecialchars
htmlentities
how could i resolve this.
When your data contains HTML tags then use
Write your code in blade file like
{!! $blog->body !!}
Try this with php syntax like
{!! $blog->body !!}
Note: Make sure that your editor sending proper html content?

React/Rails: What's the syntax for passing html inside a prop in a Rails html.erb file?

I'm trying to get the following code to work, but I know my syntax for the HTML props are wrong. (The proptypes are set to PropTypes.any.) What's the correct syntax to allow the html code to render inside the component instead of erroring out or being printed as strings? Thank you in advance!
<%= react_component("components/tooltip",
{ tooltip: '<div>Some String</div>', children: '<div>Content for tooltip</div>' }) %>
I've tried a lot of variations but they only work for react components that are rendered as react components usually do, but don't work inside the html.erb file:
<ExampleComponent prop1={["Some ", <strong>random</strong>, "words">]} /> or
<ExampleComponent prop2={<div><MyComponent></div>} />

Display Images on HTML using MongoDB, But it didn't show

I have the code backend using Node.js and Front end in HTML. I tried to get the image stored in mongo to front end. But in HTML it doesn't shows the image. But when I paste the binary data of image in img src tag it works. Help plz.
index.js
function loadImages() {
let isbn=''
let imgSource=''
if (CURRENT_URL.includes('#')) {
isbn = CURRENT_URL.substr(CURRENT_URL.indexOf('#') + 1,
CURRENT_URL.length);
console.log(isbn);
}
axios.get(baseUrlLocal + '/book/image/'+isbn)
.then(response => {
console.log(response.data)
document.getElementById('imgSource')
.setAttribute(
'src', 'data:image/png;base64,' +
btoa(unescape(encodeURIComponent(response.data))) +"'"
);
})
.catch(err => {
console.log(err);
});
}
HTML
<div class="card-body" id="image-src">
<img id="imgSource" src="" alt="Red dot" />
</div>
I don't think you can do this in node.js
document.getElementById('imgSource')
.setAttribute(
'src', 'data:image/png;base64,' +
btoa(unescape(encodeURIComponent(response.data))) +"'"
);
document object is available in your browser mate. In node js you can't just use this like that. If you want to render the image you have processed, then you might want to look for a front end template engine
like
ejs
pug
handlebars
since ejs's syntax is a little bit annoying and can be very confusing sometimes you can use an alternative like handlebars take a look at here
handle bars is like a template engine. If you are familiar with Laravel or ASP.NET's Razor blade or Angular's string interpolation techniques this is very much like that so
go to your shell and install handlebars like this
npm install --save handlebars
since this is a little too much of a topic to discuss as an answer I'll just provide you with this link a tutorial on how to install and use handle bars. try that mate you will be able to achieve what you are looking for.. Cheers ...

How to dynamically add text fields on Rails 4? (not nested)

I'm very new to Rails and I need to dynamically add/remove input fields on a "form_for" in Rails. I am using these inputs to alter a user's profile.
Here's the snippet I want to turn dynamic:
<%= f.label :languages, "Languages" %>
<%= f.text_field :languages, class: "shortInput", value: #parsed_json_user['user']['languages']%> <br />
I have seen many tutorials using nested attributes (I'm not even exactly sure about what those are) and such but I will not be using models. As you can see, I just want an object with a multitude of values (e.g. array) since I'll be using an API to update the "User" model.
I need something like:
Languages:
English remove
add new
Should I be using fields_for? Or somehow use JS or JQuery? Any help would be appreciated.
I searched everywhere for a similar question and haven't found any but if you actually know of or find one, pointing me in the right direction would be wonderful!
Thanks in advance
#languages = User's Languages
f.collection_select :user_languages[], #languages, :id, :name , {hide_label: true, :selected => #languages.first.id} , {:style => "width: 120px",:required => true}
Update: For single form, no nesting - one option is to hack together your own jquery. I had used a different site for my testing, but this Jquery example was the one I found easier. I removed the stuff about a counter for max fields ... it goes in the /app/assests/javascript/.js ...
$(document).ready(function() {
$(".add_field_button").click(function(e){ //on add input button click
e.preventDefault();
$('.input_fields_wrap').append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(".input_fields_wrap").on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
})
});
And the html code ...
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
If you're not having luck yet - Cocoon Gem or railscast 197/198 will do what you need with jquery which is dynamic. Ignore the parts about nesting and just take what you need from it.
Also, I'm still poking around in turbolinks which had an update recently...you might be able to find an answer there...probably not exactly what you would want...
From what I can tell is that is rely's on two paths you write in rails, that are then built upon via the jquery that acts on (add/delete) :before or :after the link_to_add_association or link_to_remove_association in order to add/hide fields from view on the dom & then the update button actually pushes the whole mess to through activeRecord into the database.