How could/should I state colon (punctuation) in a YAML file? - html

I am using Ruby on Rails 3.1.0 and I would like to know how to correctly state colon (punctuation) in a YAML file. I tried to support that by adding the following code in my config/locales/defaults/en.yml file
en
# ':' is the HTML code for ':'
test_key_html: Test value:
and in my view file I used
t('test_key_html')
but it doesn't work (in the front end content is displayed the "plain" Test value: text).
Is it possible? If so how?

You should be able to double quote the value:
test_key_html: "Test value:"
This avoids colon-confusion in the YAML and gets your colon into your HTML.
Consider this in irb:
>> { 'en' => { 'test_key_html' => 'Test value:' } }.to_yaml
=> "--- \nen: \n test_key_html: "Test value:"\n"

Try
raw(t('test_key_html'))
Rails 3+ automattically escapes html markup

Related

How to return number and newline with JSON

I want to return a number and a new line
{ data : "3
"}
But every time, I try to do this it is considered invalid
Update
My parser tool tries to do things with Newlines. Here is the complete screenshot:
** Update 2**
This is with jsonlint.com
The problem is that data is not a valid key (check https://www.json.org/ or Do the JSON keys have to be surrounded by quotes?), you need to use quotes for keys in order to have valid syntax. Also you need to add \n for a new line character:
{ "data": "3\n"}
I pasted this into the console without an error:
{ "data" : "3\n"}
Testing one step further:
a = { "data" : "3\n"}
a.data + "hello" // pasted into the console
produced this:
3
hello

Convert from HTML::Template to PDF:FromHtml says invalid XML

I create an HTML file using HTML::Template. The resulting code is a valid XML/HTML (check against a xml validator). But while convert to pdf using PDF::FromHTML a message of "invalid token in xml file" is found.
Trying changing the first declaration line from doctype to xml, or supressing, but nothing works. XML::Simple, PDF:API2, XML::Writer are last version.
Ay idea what is happening?
# create template object and store to verify
shout('s',"create template from $str_filepath") if ($bool_DEBUG);
$str_mytemplate = HTML::Template->new(filename => $str_filepath, case_sensitive => 0, no_includes => 1 );
$str_mytemplate->param(\%strct_toreplace);
$str_filepath = envDir('temp').newID().'.html';
shout('',"template created, storing to : $str_filepath") if ($bool_DEBUG);
if (open(FILE, '>', $str_filepath)) {
print FILE $str_mytemplate->output;
close (FILE);
}
# generate pdf from created file
shout('p',"Creating PDF ") if ($bool_DEBUG);
$pdf_this = PDF::FromHTML->new( encoding => 'utf-8' );
$pdf_this->load_file($str_filepath);
$pdf_this->convert( LineHeight => 10, Landscape => 1, PageSize => 'Letter', );
shout('p',"Display PDF") if ($bool_DEBUG);
print header(-type=>'application/pdf', -charset=>'UTF-8');
print $pdf_this->write_file();
$bool_DEBUG and shout(); are a variable and procedure to set and display messages while debugging mode.
Html code generated via template: http://www.etoxica.com/examplecode.html
Template used: http://www.etoxica.com/exampletemplate.tmpl
Message displayed:
SECTION: Creating PDF
Software error:
not well-formed (invalid token) at line 19, column 13, byte 430 at /usr/local/lib64/perl5/XML/Parser.pm line 187.
at /home/grupo/perl/usr/share/perl5/PDF/FromHTML.pm line 141.
Summary: Found the problem (I guess) ;)
Consider the following lines:
<td>
Some line of data
<br/>
A second line of data
</td>
When try to be read by PDF::FromHTML it will send a message of malformed token in the 5th line, specifically on the slash '/' from </td> tag; BUT, that is not the problem, the problem is created by the <br/> tag inside the <td></td>.
If it is changed to <br> or <br /> no error is found. I don't know if using <br> is a good html practice to xml compability, even is defined as it w3c br semantic.

show a smarty variable with html content

I have a smarty variable with html content in it like:
$html="<strong>Content</strong><br/>etc etc"
.
I try to show it html-formatted. When showing it like
{$html}
only plain text appears without formatting. I try like:
{$html|unescape}
but then the tags are shown but not applied. Do you have any suggestions?
Interestingly, none of the answers here work with Smarty 3.1.21 on CS-Cart 4.3.4. So, just to add another thought in that circumstance, use the nofilter on the $html string like so:
{$html nofilter}
You should try this:
{$html|unescape:'html'}
Also check manual:
http://www.smarty.net/docs/en/language.modifier.unescape.tpl
You can try this:
{$html|unescape: "html" nofilter}
Use {$html|unescape: "html" nofilter}
Based on the answer from Sim1-81 and ρяσѕρєя K. I want to explain why the following code works.
The unescape:"html" modifier helps to keep the special characters in place. For example, "€". (Docs).
"nofilter" flag disables $escape_html, which essentially disables the variable being wrapped with htmlspecialchars() (Docs).
Their solution helped as my case was to display a templated block of HTML passed in from a variable.
Some versions of smarty unescape is not available. If this is the case, try using escape:'htmlentitydecode'.
{$html|escape:'htmlentitydecode'}
For those who are using Smarty 2.x, the unescape method is not available, can try this instead;
{$html|html_entity_decode}
you can try :
php function symbol:
function html($str) {
$arr = array(
"<" => "<",
">" => ">",
""" => '"',
"&" => "&",
"\" => chr(92),
"&#39" => chr(39),
"'" => chr(39)
);
return nl2br(strtr($str,$arr));
}
In smarty template call:
{html({$html})}
Or without php function only smarty:
{$html|unescape:'allhtml'}
Notice: if in tpl have use reset css you can try remove it and try again.

HAML - parameter with dash

How can I convert this line
<body data-spy="abcd">
to HAML syntax?
This one returns me an error
%body{:data-spy => "abcd"}
HAML Syntax for the HTML5 Data Field:
%div{ :data => {:id => '555'} }
Now, I started messing around, and it looks like this only works with "data" -- other tags need to be:
%div{ "star-datas" => "hello!" }
Your example:
%body{:data => { :spy => 'abcd'}}
I don't know why I didn't post this in the first place. The "correct" way to write your tag, <body data-spy="abcd">, in HAML, is to skip the {} entirely and use ():
%body(data-spy="abcd")
If you're not evaluating the values of the attributes as Ruby, you shouldn't be using {:key => value} syntax at all. Stick to (key="value") for static HTML attributes.
Original answer:
HAML has a specific syntax for working with data attributes which CrazyVipa's answer summarizes nicely.
For the sake of completeness, I'll point out that you can also use quoted symbol syntax, both here and anywhere else in Ruby that you want to use a hyphen in a symbol:
%body{ :"data-spy" => "abcd" }
In general, :"text" is equivalent to "text".to_sym, allowing your symbol to contain characters it normally couldn't due to parser limitations. The following are all valid symbols:
:"symbol with spaces"
:"symbol-with-hyphens"
:"symbol
with
newlines"
:"def my_func(); puts 'ok'; end"
Note that quoted symbols will not work with Ruby 1.9's new hash syntax:
{ :"key-1" => "value" } # works in 1.8/1.9
{ "key-1": "value" } # syntax error
For HAML ruby compiler:
%div{data: {some_hyphenated_id: 'value'}}
and HAML automatically converts underscores to hyphens so I get:
<div data-some-hyphenated-id="value"></div>
FYI: if you need empty attribute just use true instead of 'value'
Example:
Haml:
%div{data: {topbar: true}}
%div{data: {image_carousel: true}}
HTML:
<div data-topbar></div>
<div data-image-carousel></div>
To be more specific this syntax is valid for ruby haml gem as well as grunt task grunt-haml with language set to ruby (requires mentioned ruby haml gem installed)

How to HTML encode/escape a string? Is there a built-in?

I have an untrusted string that I want to show as text in an HTML page. I need to escape the chars '<' and '&' as HTML entities. The less fuss the better.
I'm using UTF8 and don't need other entities for accented letters.
Is there a built-in function in Ruby or Rails, or should I roll my own?
Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.
CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo "bar" <baz>"
The h helper method:
<%=h "<p> will be preserved" %>
In Ruby on Rails 3 HTML will be escaped by default.
For non-escaped strings use:
<%= raw "<p>hello world!</p>" %>
ERB::Util.html_escape can be used anywhere. It is available without using require in Rails.
An addition to Christopher Bradford's answer to use the HTML escaping anywhere,
since most people don't use CGI nowadays, you can also use Rack:
require 'rack/utils'
Rack::Utils.escape_html('Usage: foo "bar" <baz>')
You can use either h() or html_escape(), but most people use h() by convention. h() is short for html_escape() in rails.
In your controller:
#stuff = "<b>Hello World!</b>"
In your view:
<%=h #stuff %>
If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as <b>Hello World!</b>.
It will appear an be displayed as <b>Hello World!</b>
Comparaison of the different methods:
> CGI::escapeHTML("quote ' double quotes \"")
=> "quote ' double quotes ""
> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote ' double quotes ""
> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote ' double quotes ""
I wrote my own to be compatible with Rails ActiveMailer escaping:
def escape_html(str)
CGI.escapeHTML(str).gsub("'", "'")
end
h() is also useful for escaping quotes.
For example, I have a view that generates a link using a text field result[r].thtitle. The text could include single quotes. If I didn't escape result[r].thtitle in the confirm method, the Javascript would break:
<%= link_to_remote "#{result[r].thtitle}", :url=>{ :controller=>:resource,
:action =>:delete_resourced,
:id => result[r].id,
:th => thread,
:html =>{:title=> "<= Remove"},
:confirm => h("#{result[r].thtitle} will be removed"),
:method => :delete %>
<a href="#" onclick="if (confirm('docs: add column &apos;dummy&apos; will be removed')) { new Ajax.Request('/resource/delete_resourced/837?owner=386&th=511', {asynchronous:true, evalScripts:true, method:'delete', parameters:'authenticity_token=' + encodeURIComponent('ou812')}); }; return false;" title="<= Remove">docs: add column 'dummy'</a>
Note: the :html title declaration is magically escaped by Rails.