show a smarty variable with html content - html

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.

Related

How to construct json text using string?

I'm trying to construct json text as show below. But the variables such as $token, $state, $failedServers are not been replaced with its value. Note- I don't want to use any module specifically for this to work, I just want some plain string to work. Can anyone help me ?
my $json = '{"serverToken":"$token", "state":"$state","parameters" :"$failedServers"}';
current output was:
{"serverToken":"$token", "state":"$state","parameters" :"$failedServers"}
needed output format:
{"serverToken":"1213", "state":"failed","parameters" :"oracleapps.veeralab.com,suntrust.com"}
Your variables are not being replaced, because they are inside of a single-quoted string--that is, they are inside a string quoted by ' characters. This prevents variable substitution.
You will also be much better off creating JSON using a JSON library, such as this one. Simply using a quoted string is very dangerous. Suppose your one of your variables ends up containing a special character; you will end up with invalid JSON.
{"serverToken":"123"ABC", "state":"offline", "paramameters":"bugs"}
If your variables come from user input, really bad things could happen. Imagine that $token is set to equal foo", "state":"online", "foo":"bar. Your resulting JSON structure would be:
{"serverToken":"foo", "state":"online", "foo":"bar", "state":"offline" ...
Certainly not what you want.
Possible solutions:
The most blatantly obvious solution is simply not to the ' quote character. This has the drawback of requiring you to escape your double quote (") characters, though, but it's easy:
my $json = "{\"serverToken\":\"$token\", \"state\":\"$state\",\"parameters\" :\"$failedServers\"}";
Another option is to use sprintf:
my $json = sprintf('{"serverToken":"%s", "state":"%s", "parameters":"%s"}', $token, $state, $failedServers);
But by far, the best solution, because it won't break with wonky input, is to use a library:
use JSON;
my $json = encode_json( {
serverToken => $token,
state => $state,
paramaters => $failedServers
} );

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 could/should I state colon (punctuation) in a YAML file?

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

Strip html from string Ruby on Rails

I'm working with Ruby on Rails, Is there a way to strip html from a string using sanitize or equal method and keep only text inside value attribute on input tag?
If we want to use this in model
ActionView::Base.full_sanitizer.sanitize(html_string)
which is the code in "strip_tags" method
There's a strip_tags method in ActionView::Helpers::SanitizeHelper:
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_tags
Edit: for getting the text inside the value attribute, you could use something like Nokogiri with an Xpath expression to get that out of the string.
Yes, call this: sanitize(html_string, tags:[])
ActionView::Base.full_sanitizer.sanitize(html_string)
White list of tags and attributes can be specified as bellow
ActionView::Base.full_sanitizer.sanitize(html_string, :tags => %w(img br p), :attributes => %w(src style))
Above statement allows tags img, br and p and attributes src and style.
I've used the Loofah library, as it is suitable for both HTML and XML (both documents and string fragments). It is the engine behind the html sanitizer gem. I'm simply pasting the code example to show how simple it is to use.
Loofah Gem
unsafe_html = "ohai! <div>div is safe</div> <script>but script is not</script>"
doc = Loofah.fragment(unsafe_html).scrub!(:strip)
doc.to_s # => "ohai! <div>div is safe</div> "
doc.text # => "ohai! div is safe "
How about this?
white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
WHITELIST = ['p','b','h1','h2','h3','h4','h5','h6','li','ul','ol','small','i','u']
[Your, Models, Here].each do |klass|
klass.all.each do |ob|
klass.attribute_names.each do |attrs|
if ob.send(attrs).is_a? String
ob.send("#{attrs}=", white_list_sanitizer.sanitize(ob.send(attrs), tags: WHITELIST, attributes: %w(id style)).gsub(/<p>\s*<\/p>\r\n/im, ''))
ob.save
end
end
end
end
If you want to remove all html tags you can use
htm.gsub(/<[^>]*>/,'')
This is working for me in rails 6.1.3:
.errors-description
= sanitize(message, tags: %w[div span strong], attributes: %w[class])
You can do .to_plain_text:
#my_string = <p>My HTML String</p>
#my_string.to_plain_text
=> My HTML String

How can I remove unused, nested HTML span tags with a Perl regex?

I'm trying to remove unused spans (i.e. those with no attribute) from HTML files, having already cleaned up all the attributes I didn't want with other regular expressions.
I'm having a problem with my regex not picking the correct pair of start and end tags to remove.
my $a = 'a <span>b <span style="color:red;">c</span> d</span>e';
$a =~ s/<span\s*>(.*?)<\/span>/$1/g;
print "$a\
returns
a b <span style="color:red;">c d</span>e
but I want it to return
a b <span style="color:red;">c</span> de
Help appreciated.
Try HTML::Parser:
#!/usr/bin/perl
use strict;
use warnings;
use HTML::Parser;
my #print_span;
my $p = HTML::Parser->new(
start_h => [ sub {
my ($text, $name, $attr) = #_;
if ( $name eq 'span' ) {
my $print_tag = %$attr;
push #print_span, $print_tag;
return if !$print_tag;
}
print $text;
}, 'text,tagname,attr'],
end_h => [ sub {
my ($text, $name) = #_;
if ( $name eq 'span' ) {
return if !pop #print_span;
}
print $text;
}, 'text,tagname'],
default_h => [ sub { print shift }, 'text'],
);
$p->parse_file(\*DATA) or die "Err: $!";
$p->eof;
__END__
<html>
<head>
<title>This is a title</title>
</head>
<body>
<h1>This is a header</h1>
a <span>b <span style="color:red;">c</span> d</span>e
</body>
</html>
Regex is insufficiently powerful to parse HTML (or XML). Any regex you can come up with will fail to match various formulations of even valid HTML (let alone real-world tag soup).
This is a nesting problem. Regex can't normally handle nesting at all, but Perl has a non-standard extension to support regex recursion: (?n), where n is the group number to recurse into. So something like this would match both spans in your example:
(<span[^>]*>.*+(?1)?.*+<\/span>)
See perlfaq 6.11.
Unfortunately this still isn't enough, because it needs to be able to count both attributed and unattributed <span> start-tags, allowing the </span> end-tag to close either one. I can't think of a way this can be done without also matching the attributes span start-tags.
You need an HTML parser for this, and you should be using one anyway because regex for HTML/XML is decidedly the Wrong Thing.
Don't use regexps for processing (HTML ==) XML. You never know what input you'll get. Consider this, valid HTML:
a <span>b <span style="color:red;" title="being closed with </span>">c</span> de
Would you have thought of that?
Use an XML processor instead.
Also see the Related Questions (to the right) for your question.
With all your help I've published a script that does everything I need.
http://github.com/timabell/decrufter/