Add class for css in ejs by node - css

Please mind the environment of this Application. I'm using
Windows
NPM ,Express
MySQL
This is the code in ejs template. example.ejs
<% if (message) { %>
<p class="alert " id="errorMessage">
<%= message %>
</p>
<% } %>
I want to add class to p.
This is what I am doing but didn't work.
messages = "Password Successfully Changed";
jQuery('#errorMessage').addClass('successMessage');
res.render('profile',{page_title:"My Profile",data:rows,message: messages});

I got the answer.
var messageData = {
message : "Password Successfully Changed",
class : "successMessage"
};
res.render('profile',{page_title:"My Profile",data:rows,message: messageData });
then on template side.
<% if (globalMessage) { %>
<p class="alert <%= globalMessage.class %>" id="errorMessage">
<%= globalMessage.message %>
</p>
<% } %>

Related

Ruby On Rails 7.0 invalid? set true in console but not in view

I´m trying to avoid to update an empty name for #post.
I´m beginner in RoR and I don´t understand why in terminal I got #post.invalid? => true but in my view edit.html.erb #post.invalid? => false
posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, :only => [:edit, :show, :update, :destroy]
def index
#posts = Post.all
respond_to do |format|
format.html
format.json { render json: #posts }
end
end
def show
respond_to do |format|
format.html
format.json { render json: #post }
end
end
def edit
end
def update
if #post.update(post_params)
redirect_to posts_path, success: "Post updated"
else
puts #post.invalid? # write true
render 'edit'
end
end
def new
#post = Post.new
end
def create
post = Post.create(post_params)
redirect_to post_path(post.id), success: "Post created"
end
def destroy
#post.destroy
redirect_to posts_path, success: "Post deleted"
end
private
def post_params
params.require(:post).permit(:name, :content)
end
def set_post
#post = Post.find(params[:id])
end
end
post.rb
class Post < ApplicationRecord
validates :name, presence: true
def as_json(options = nil)
super(only: [:name, :id, :created_at] )
end
end
edit.html.erb
<h1>Editer l´article</h1>
<%= #post.invalid? %> <!-- write false -->
<% if #post.invalid? %> <!-- return false -->
<div class="alert alert-danger">
<% #post.errors.full_messages.each do |message| %>
<%= message %>
<% end %>
</div>
<% end %>
<%= form_for #post do |f| %>
<div class="form-group">
<label>Titre de l´article</label>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<label>Contenu de l´article</label>
<%= f.text_area :content, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.submit "Modifier l´article", class: 'btn btn-primary' %>
</div>
<% end %>
I´m confused, someone has got an idea ?
The methods valid? and invalid? all keep running the validation methods every time they are called, and therefore potentially change the state of the model.
If you want to just check for validity when validation has already been run, you should instead use #post.errors.present? or #post.errors.blank? which will never change the status, only read existing errors (that were added in your case when the call to update failed.
Additionally (even if it´s not the case here) calling valid? and invalid? without a context will clear out errors that had been added with validations like validate ..., on: :update.
The solution I found was a combination of #rewritten´s answer and this one.
So...
<h1>Editer l´article</h1>
<% if #post.errors.present? %>
<div class="alert alert-danger">
<% #post.errors.full_messages.each do |message| %>
<%= message %>
<% end %>
</div>
<% end %>
<%= form_for #post, data: { turbo: false} do |f| %>
<div class="form-group">
<label>Titre de l´article</label>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<label>Contenu de l´article</label>
<%= f.text_area :content, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.submit "Modifier l´article", class: 'btn btn-primary' %>
</div>
<% end %>

EJS conditional statement change CSS

I have loop in EJS and I want to set css based on my data:
<% dummies.forEach(function(dummy) { %>
<div class="panel panel-???">
</div>
<% }) %>
my data:
var dummies = [{
type: "funny",
sure: "Yes" // this should generate panel-success
}, {
type: "funny", // this should generate panel-a
sure: "No"
}, {
type: "happy", // this should generate panel-b
sure: "No",
}];
So whenever sure attribute is Yes, it generates panel-success. Otherwise, it generates css based on type attribute.
Please help.
First create object like this:
<%
let cssClass = {
funny: {
Yes: "success",
No: "a"
},
happy: {
No: "b"
}
}
%>
Then you should just output value in template:
<% dummies.forEach(function(dummy) { %>
<div class="panel panel-<%= cssClass[dummy.type][dummy.sure] %>">
</div>
<% }) %>
Try using this code...
<% dummies.forEach(function(dummy) { %>
<div class="panel panel-
<% if (dummy.sure==="yes") { %>
success
<% else %>
<%= dummy.type %>
>
</div>
<% }) %>
You can just wrap your logic inside the EJS operators. It looks a little messy but it is what it is. Depending on how your server side is set up, you could also pass in parameters from the server side, instead of doing the logic on the client side.
The best way would depend on where the heavy lifting is done as far as trips to the database and any other logic going on.
I think this code will help :
<a class="<%= 1==2 ? 'active' : '' %>" href="#"></a>

Creating article pagination

Hi I'm using silverstripe 2.4.7 and I'm having difficulty getting the pagination to work. I've created a function in my page.php to get the latest articles like so
function AllNewsPosts($num=1) {
$news = DataObject::get_one("NewsHolder");
return ($news) ? DataObject::get("NewsEntry", "ParentID > 0", "Date DESC", "", $num) : false;
}
Then when i put this function into the control and pagination tags one article shows up however the links to the concurrent articles do not work - essentially the pagination is not working and I'm not sure how to fix it
<% if AllNewsPosts %>
<% control AllNewsPosts %>
<div class="event">
<h2>$MenuTitle |<span class="date"> $Date.Time $Date.Long</span></h2>
<p>$Content.FirstParagraph</p>
See more about this event
</div>
<% end_control %>
<% else %>
<div class="no-entry">'There are no entries'</div>
<% end_if %>
<% if AllNewsPosts.MoreThanOnePage %>
<div id="PageNumbers">
<p>
<% if AllNewsPosts.NotFirstPage %>
<a class="prev" href="$AllNewsPosts.PrevLink" title="View the previous page"><span class="yellow-background">Prev</span></a>
<% end_if %>
<span>
<% control AllNewsPosts.PaginationSummary(0) %>
<% if CurrentBool %>
<span class="current">$PageNum</span>
<% else %>
<% if Link %>
$PageNum
<% else %>
…
<% end_if %>
<% end_if %>
<% end_control %>
</span>
<% if AllNewsPosts.NotLastPage %>
<a class="next" href="$AllNewsPosts.NextLink" title="View the next page"><span class="yellow-background">Next</span></a>
<% end_if %>
</p>
</div>
<% end_if %>
Any help is much appreciated
Note: The following answer is for Silverstripe 2.4. This should not be used for Silverstripe 3.0+ sites. From 3.0 and onwards the PaginatedList object makes pagination much easier.
You are not setting a limit on how many entries to retrieve in your query, or where to start from.
The following tutorial explains how to apply pagination to a set of data objects exactly as you are trying to do:
http://www.ssbits.com/tutorials/2010/paginating-a-filtered-dataobjectset/
Here is an attempt at altering your function to include limit and start as needed for pagination:
PHP
function AllNewsPosts() {
if(!isset($_GET['start']) || !is_numeric($_GET['start']) || (int)$_GET['start'] < 1)
{
$_GET['start'] = 0;
}
$SQL_start = (int)$_GET['start'];
$newsEntries = DataObject::get('NewsEntry', '', 'Date DESC');
$doSet = new DataObjectSet();
foreach ($newsEntries as $newsEntry) {
if ($newsEntry->canView()) {
$doSet->push($newsEntry);
}
}
$doSet->setPageLimits($SQL_start, 10, $doSet->Count());
return $doSet;
}
Note the above will display 10 items per page. You can change this to however you need per page.

ASP.net mvc how to comment out html code in page

Is there an easy way to comment out a loop which renders some html and has inline html without deleting anything? I am copying and pasting some code from another project to rebuild a new public front end from a working internal backend.
Below is an example of a sitation in which it would be nice...in asp.net MVC 2
<%
List<VehicleBodyTypeListItem> lstBodyTypes = (List<VehicleBodyTypeListItem>)ViewData["ddBodyType"];
foreach (VehicleBodyTypeListItem bodyType in lstBodyTypes)
{
%>
<a href="<%= Url.Action( "Search", new { BodyTypeID=bodyType.BodyTypeID, BodyType= Url.Encode( Html.WebLinkify( bodyType.BodyType))}) + (string)ViewData["httpCriteria"] %>">
<%= Html.Encode( String.Format( "{0} ({1})", bodyType.BodyType, bodyType.Count.ToString())) %> </a>
<br />
<%
}
%>
I have not completed the method that populates this list yet, and have about 5 more like it further down the page.
The keyboard shortcut is, if you select the section you want commented out is: CTRL + K + C will comment out code. CTRL + K + U will uncomment the code.
Comment a block of code by enclosing it in #* and *#
Do you mean adding comments to the code. If so you just need to add //. Like here:
<%
List<VehicleBodyTypeListItem> lstBodyTypes = (List<VehicleBodyTypeListItem>)ViewData["ddBodyType"];
foreach (VehicleBodyTypeListItem bodyType in lstBodyTypes) // Here there's a comment
{
%>
<a href="<%= Url.Action( "Search", new { BodyTypeID=bodyType.BodyTypeID, BodyType= Url.Encode( Html.WebLinkify( bodyType.BodyType))}) + (string)ViewData["httpCriteria"] %>">
<%= Html.Encode( String.Format( "{0} ({1})", bodyType.BodyType, bodyType.Count.ToString())) %> </a>
<br />
<%
}
%>

ASP.NET Error CS1026: ) expected?

why do I see the CS1026 error:) expected at the line below ?
<%=Html.BeginForm("AddAdvertisement", "Advertisement"){%> //here
hello
<%} %>
I think you want this instead (docs):
<% using(Html.BeginForm("AddAdvertisement", "Advertisement")) { %> //here
hello
<% } %>

Resources