.each do else statement in HTML Slim - html

I have an HTML Slim document and I would like to know how to put an else statement if no results are found. Here is my current code:
- #books.each do |rep|
.row
.large-12.columns
.bookinfo
.name= book.name
= book.title_name
br
= mail_to author.email, author.email
br
a.phonenumber href="tel:#{ author.phone }"= author.phone
Sorry, I am not at all familiar with HTML Slim and I have very little experience with Ruby. Thanks in advance!

What about something like
- if #books.present?
- #books.each do |rep|
.row
... draw the book
- else
.row No Books Here

Related

only <a> tag execute from html content in rails

My problem is only execute tag from html content in rails.
I'm using raw, sanitize but all html tag executed
Example
#input = 'go <b>bold</b> <i>bat</i>'
<%=raw #input%>
<%=sanitize #input%>
there are same output: go bold bat
my propose is output: go <b>bold</b> <i>bat</i>
I implementing hash tag like facebook, but user input not safe many hash tag and many html tags
any idea?
thank you
I also struggled with this and the following will help:
#input = 'go'
#input += '<b>bold</b> <i>bat</i>'.encode {xml: :text}
This will format the HTML special characters as raw symbols. More at the docs for String#encode.
You can do:
<% #input = 'go'.html_safe+'<b>bold</b> <i>bat</i>' %>
<%= raw #input %>
#input = 'go'.html_safe
#input += ' <b>bold</b> <i>bat</i>'
<%= #input %>

Controlling the existence of an attribute

I have a problem with the Slim template engine in a Sinatra project. I have an edit form to be filled when the route is triggered. There is an issue with HTML select option. I need something like this when the edit form is loaded. Notice that Mrs. option is selected:
<select name="person[title]" id="person[title]">
<option value="Mr.">Mr.</option>
<option value="Mrs." selected>Mrs.</option>
</select>
I tried:
option[value="Mrs." "#{person.title == :mrs ? 'selected' : ''}"]
The exception was about an attribute error. Then I tried something like this:
option[value="Mrs." selected="#{person.title == :mrs ? true : false}"]
but then the output was something like this:
<option value"Mrs." selected="false">Mrs.</option>
I guess the string"false" is interpreted as true. That failed. I tried some combinations with round brackets but couldn't get it to work.
How could I set the selected attribute of an option in a select list in Slim?
For an attribute, you can write ruby code after the =, but if the ruby code has spaces in it, you have to put parentheses around the ruby code:
option[value="1" selected=("selected" if #title=="Mrs.")] "Mrs."
See "Ruby attributes" here: http://rdoc.info/gems/slim/frames.
The brackets are optional, so you can also write it like this:
option value="1" selected=("selected" if #title=="Mrs.") "Mrs."
Or, instead of brackets, you can use a different delimiter:
option {value="1" selected=("selected" if #title=="Mrs.")} "Mrs."
Here it is with some code:
slim.slim:
doctype html
html
head
title Slim Examples
meta name="keywords" content="template language"
body
h1 Markup examples
p This example shows you how a basic Slim file looks like.
select
option[value="1" selected=("selected" if #title=="Mr.")] "Mr."
option[value="2" selected=("selected" if #title=="Mrs.")] "Mrs."
Using Slim in a standalone ruby program without rails:
require 'slim'
template = Slim::Template.new(
"slim.slim",
pretty: true #pretty print the html
)
class Person
attr_accessor :title
def initialize title
#title = title
end
end
person = Person.new("Mrs.")
puts template.render(person)
--output:--
<!DOCTYPE html>
<html>
<head>
<title>
Slim Examples
</title>
<meta content="template language" name="keywords" />
</head>
<body>
<h1>
Markup examples
</h1>
<p>
This example shows you how a basic Slim file looks like.
</p>
<select><option value="1">"Mr."</option><option selected="selected" value="2">"Mrs."</option></select>
</body>
</html>
I guess the string "false" is interpreted as true.
Yes. The only things that evaluate to false are false itself and nil. Any number(including 0), any string (including ""), and any array(including []), etc. are all true.
Not pertinent to your problem, but perhaps useful to some future searcher...I guess Slim looks up instance variables in whatever object you pass as an argument to render. So if you want to provide a whole bunch of values for the template, you can write:
require 'slim'
template = Slim::Template.new(
"slim.slim",
pretty: true #pretty print the html
)
class MyVals
attr_accessor :count, :title, :animals
def initialize count, title, animals
#count = count
#title = title
#animals = animals
end
end
vals = MyVals.new(4, "Sir James III", %w[ squirrel, monkey, cobra ])
puts template.render(vals)
slim.slim:
doctype html
html
head
title Slim Examples
meta name="keywords" content="template language"
body
p =#count
p =#title
p =#animals[-1]
Neither OpenStruct nor Struct work with render() even though they seem like natural candidates.

Indenting generated markup in Jekyll/Ruby

Well this is probably kind of a silly question but I'm wondering if there's any way to have the generated markup in Jekyll to preserve the indentation of the Liquid-tag. World doesn't end if it isn't solvable. I'm just curious since I like my code to look tidy, even if compiled. :)
For example I have these two:
base.html:
<body>
<div id="page">
{{content}}
</div>
</body>
index.md:
---
layout: base
---
<div id="recent_articles">
{% for post in site.posts %}
<div class="article_puff">
<img src="/resources/images/fancyi.jpg" alt="" />
<h2>{{post.title}}</h2>
<p>{{post.description}}</p>
Read more
</div>
{% endfor %}
</div>
Problem is that the imported {{content}}-tag is rendered without the indendation used above.
So instead of
<body>
<div id="page">
<div id="recent_articles">
<div class="article_puff">
<img src="/resources/images/fancyimage.jpg" alt="" />
<h2>Gettin' down with responsive web design</h2>
<p>Everyone's talking about it. Your client wants it. You need to code it.</p>
Read more
</div>
</div>
</div>
</body>
I get
<body>
<div id="page">
<div id="recent_articles">
<div class="article_puff">
<img src="/resources/images/fancyimage.jpg" alt="" />
<h2>Gettin' down with responsive web design</h2>
<p>Everyone's talking about it. Your client wants it. You need to code it.</p>
Read more
</div>
</div>
</div>
</body>
Seems like only the first line is indented correctly. The rest starts at the beginning of the line... So, multiline liquid-templating import? :)
Using a Liquid Filter
I managed to make this work using a liquid filter. There are a few caveats:
Your input must be clean. I had some curly quotes and non-printable chars that looked like whitespace in a few files (copypasta from Word or some such) and was seeing "Invalid byte sequence in UTF-8" as a Jekyll error.
It could break some things. I was using <i class="icon-file"></i> icons from twitter bootstrap. It replaced the empty tag with <i class="icon-file"/> and bootstrap did not like that. Additionally, it screws up the octopress {% codeblock %}s in my content. I didn't really look into why.
While this will clean the output of a liquid variable such as {{ content }} it does not actually solve the problem in the original post, which is to indent the html in context of the surrounding html. This will provide well formatted html, but as a fragment that will not be indented relative to tags above the fragment. If you want to format everything in context, use the Rake task instead of the filter.
-
require 'rubygems'
require 'json'
require 'nokogiri'
require 'nokogiri-pretty'
module Jekyll
module PrettyPrintFilter
def pretty_print(input)
#seeing some ASCII-8 come in
input = input.encode("UTF-8")
#Parsing with nokogiri first cleans up some things the XSLT can't handle
content = Nokogiri::HTML::DocumentFragment.parse input
parsed_content = content.to_html
#Unfortunately nokogiri-pretty can't use DocumentFragments...
html = Nokogiri::HTML parsed_content
pretty = html.human
#...so now we need to remove the stuff it added to make valid HTML
output = PrettyPrintFilter.strip_extra_html(pretty)
output
end
def PrettyPrintFilter.strip_extra_html(html)
#type declaration
html = html.sub('<?xml version="1.0" encoding="ISO-8859-1"?>','')
#second <html> tag
first = true
html = html.gsub('<html>') do |match|
if first == true
first = false
next
else
''
end
end
#first </html> tag
html = html.sub('</html>','')
#second <head> tag
first = true
html = html.gsub('<head>') do |match|
if first == true
first = false
next
else
''
end
end
#first </head> tag
html = html.sub('</head>','')
#second <body> tag
first = true
html = html.gsub('<body>') do |match|
if first == true
first = false
next
else
''
end
end
#first </body> tag
html = html.sub('</body>','')
html
end
end
end
Liquid::Template.register_filter(Jekyll::PrettyPrintFilter)
Using a Rake task
I use a task in my rakefile to pretty print the output after the jekyll site has been generated.
require 'nokogiri'
require 'nokogiri-pretty'
desc "Pretty print HTML output from Jekyll"
task :pretty_print do
#change public to _site or wherever your output goes
html_files = File.join("**", "public", "**", "*.html")
Dir.glob html_files do |html_file|
puts "Cleaning #{html_file}"
file = File.open(html_file)
contents = file.read
begin
#we're gonna parse it as XML so we can apply an XSLT
html = Nokogiri::XML(contents)
#the human() method is from nokogiri-pretty. Just an XSL transform on the XML.
pretty_html = html.human
rescue Exception => msg
puts "Failed to pretty print #{html_file}: #{msg}"
end
#Yep, we're overwriting the file. Potentially destructive.
file = File.new(html_file,"w")
file.write(pretty_html)
file.close
end
end
We can accomplish this by writing a custom Liquid filter to tidy the html, and then doing {{content | tidy }} to include the html.
A quick search suggests that the ruby tidy gem may not be maintained but that nokogiri is the way to go. This will of course mean installing the nokogiri gem.
See advice on writing liquid filters, and Jekyll example filters.
An example might look something like this: in _plugins, add a script called tidy-html.rb containing:
require 'nokogiri'
module TextFilter
def tidy(input)
desired = Nokogiri::HTML::DocumentFragment.parse(input).to_html
end
end
Liquid::Template.register_filter(TextFilter)
(Untested)

Rails: Adding an empty tag plus content to link_to

I'm trying to generate a link using the link_to helper that will output the following HTML:
<i class="some_class"></i>Link Name
However the code I'm using to try to accomplish this:
link_to(tag("i", class: options[:icon]) + title, url)
...is outputting:
<i class="some_class">Link Name</i>
Why is it doing this, and how can I fix it? Thanks.
EDIT:
I believe I found the issue.
<i> tags are not self-closable tags in HTML5. Therefore the text after the i is treated as that element's content.
Have you tried using the block format of link_to?
<%= link_to url do %>
<%= tag("i", class: options[:icon]) %>
Link Name
<% end %>
Tweak that to your needs and maybe you'll get what you're looking for.
This is the icon tag helper I use in my applications which I frequently pass as the first argument to link_to, which can either be used to create a icon tag alone, or an icon tag followed by text.
def icon_tag(icon, *args)
options = args.extract_options!
text = args.first || options.delete(:text)
if text.nil?
content_tag :i, "", class: ["icon", "icon-#{icon}"] + options[:class].to_a
else
"#{icon_tag icon} #{text}".html_safe
end
end

How to let special XML chars unconverted in flex?

That's my xml node:
<node att="something < something else"> </node>
When i write in my code :
trace(xml.node.#att.toString());
it prints out the string :
something < something else
My problem is that i need to print out the orriginal string:
something $lt; something else //put $ instead of &
Does anyone know how to solve this?
Thanks in advance.
Hey !
Just tried this and it seems to work... : )
var xml:XML=<node att="something < something else"> </node>;
trace(xml.toXMLString());//<node att="something < something else"/>
trace(xml.#att.toXMLString());//something < something else
The basic XML Parser will unespace them.
If you want the converted char again, you'll need to reconvert it again using ActionScript 3.
You can also convert it twice, using &lt;
Option 1 - USE <![CDATA[ ]]>
<chapter title="hello" nr="111" src="">
<page>
<text><![CDATA[To adjust <br/><br/>. . . ]]></text>
<text><![CDATA[To adjust <br/><br/>. . . ]]></text>
</page>
</chapter>
Option 2 - use < and > for < and >
Then <br/> = <b/>