Error in Mako: "expected %>", escaping % - mako

I'm currently writing Javascript in a mako file, and on one line, I have to check whether two strings are equal. The string I'm checking against has "<%text" within it, so I used to get an error saying there's no tag named text. I escaped that by adding a second % to get "<%%text". But now, I'm getting the following error.
SyntaxException: Expected: %> in file file.mako
What is the problem?

"<%" and "%>" are reserved symbols in Mako. If they appear in your template, Mako will assume that you mean to escape a python code block. Here is an example of what I mean:
"""
<%
some_var = 'foo'
other_var = '{0} bar'.format(some_var)
%>
"""
Take a look at http://docs.makotemplates.org/en/latest/syntax.html#python-blocks for more details
Excuse the quotes, "<%" and "%>" are also reserved symbols in the Stack Overflow WYSIWYG editor.
If the Javascript variables you are comparing contain reserved symbols, you will have to find another way of comparing them. Perhaps you could use the unicode entity for the percent sign:
For example:
if ('<%' == '<\u0025') {
alert('success!');
}

I just had a broken string variable which broke the logic, and fail on the un-related <% ... %>
Example:
<%
variable = 'this won't work'
# ^^^
%>

Related

How to only make links html safe and ignore other html tags in Rails

I have a requirement where I need to make links clickable in text while keeping any other html tags as text (not html_safe). This means I cannot make the entire text html_safe as that will render the other html tags and I cannot sanitize the text and remove the other html tags. I've seen other websites handle this by making the html_safe links and other text on their own lines. It looks like the following when inspecting the html.
<span>
"This is an "
https://example.com/
"other <b>HTML</b>"
</span>
What would be the best way to do this in Rails 4?
When you call .html_safe on a string your actually getting an object that behaves like a string but is a ActiveSupport::SafeBuffer. When you append a string to a ActiveSupport::SafeBuffer its automatically escaped. Lets say you want to construct a span where the text is user input:
'<span>'.html_safe + text +'</span>'.html_safe
In this case we are safe against an XXS attack as the user originated text is automatically escaped:
irb(main):004:0> "<span>".html_safe + "<script>alert('You have been haxxored!')</script>" + "</span>".html_safe
=> "<span><script>alert('You have been haxxored')</script></span>"
That's what happens automatically when you output a variable in your views as the view is constructed as a ActiveSupport::SafeBuffer. Whenever you output a regular string it will be automatically escaped thus its secure by default.
Of course there is always going to be a huge number of programmers that just give proceed to give themselves a XSS vulnerability out of ignorance:
# WAAAH! Rails is escaping my tags! Bad rails!
'<span>'+ text +'</span>'.html_safe
Another way to approach the problem is to use the tag helpers, partials or Nokogiri instead of using string concatenation to construct HTML which in itself is tedious, borderline unreadible and error prone.
I was able to get this working using the following.
#module ApplicationHelper
def url_regexp
#url_regexp ||= %r{
(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)
(?:\([-A-Z0-9+&##\/%=~_|$?!:,.]*\)|
[-A-Z0-9+&##\/%=~_|$?!:,.])*
(?:\([-A-Z0-9+&##\/%=~_|$?!:,.]*\)|
[A-Z0-9+&##\/%=~_|$])
}ix
end
#in the view
<%- "This is a test https://example.com".partition(url_regexp).each do |text| %>
<%- if text =~ url_regexp %>
<%= "<a href='#{text}' target='_blank'>#{text}</a>".html_safe %>
<%- else %>
<%= text %>
<% end %>

node.js: is there no way to put HTML into i18n-node JSON translation files?

The question says it all. If I put HTML directly into the (JSON-formatted) translation file, like this:
"test_html" : "click <a href='http://stackoverflow.com/'>here</a>",
I get this in my HTML:
click <a href='http://stackoverflow.com/'>here</a>
I also tried combining this in my translation file:
"test_html_placeholder" : "click %shere%s",
With this in my HTML:
<%= __('test_html_placeholder', '', '') %>
But got similar results.
The only thing I can get to work is this clumsiness:
"test_html_pre" : "click ",
"test_html_link" : "here",
"test_html_post" : ".",
with this:
<%= __('test_html_pre') %><%= __('test_html_link') %><%= __('test_html_post') %>
But it's so cumbersome as to be almost not worth doing, and moreover the word order in some languages would force me to put some empty strings in my translation files, which i18n-node doesn't seem to like as it spits out the key (attribute) name when it
encounters an empty string.
I also tried using "\" as an escape character in front of the symbols, but I got an invalid JSON error when I lifted sails (restarted the server).
Any ideas, workarounds? I'm using sails.js, it wasn't my decision but I'm stuck with it and it comes with i18n-node. It's kind of late in the day on this project to consider using another library, but not completely out of the question.
beside of any upcoming discussion whether to include (html-)code in language files or not:
try to use
<%- __('click') %>
instead of
<%= __('click') %>
in ejs (the sails default template engine) a '<%=' will escape any html tags while '<%-' puts output as is without touching it. I am pretty sure you'll find unescaped html in your .json files. i18n doesn't do any transformation other than JSON.stringify() but almost all template engines do escape strings by default to prevent xssi.
For those using pug/jade, you can use
!{ __('key_for_your_text') }
Another option for pug is using
p!= __('key_for_your_text')

Yahoo Pipes and Regex with an html formatting issue

I am struggling to see how to use the regex to add a non-printable carriage return character into an html string.
Its a WordPress thing in that to auto-embed a video I need to put the URL on its own line in the html.
First I use a regex:
In item.vid_src replace ($) with \\r$1
s is checked.
After which I am using a loop with a string builder in it - I am prefixing vid_src to the start of description thus:
item.vid_src
<br><br>
item.description
assign results to item.description
Before I include the Regex module in the pipe I get this:
http://www.youtube.com/watch?v=THA_5cqAfCQ<br><br><p><h1 class="MsoNormal">Cheetahs on
the edge</h1>
But I need this:
http://www.youtube.com/watch?v=THA_5cqAfCQ
<br><br><p><h1 class="MsoNormal">Cheetahs on the edge</h1>
Adding the regex module I get this:
http://www.youtube.com/watch?v=THA_5cqAfCQ\r<br><br><p><h1 class="MsoNormal">
Cheetahs on the edge</h1>
Clearly its inserting exactly what I have asked for, but It is not what I was expecting, I need to get the html formatted with the newline. Does anybody have an insight as to how to tackle the problem?

How can i convert/replace every newline to '<br/>'?

set tabstop=4
set shiftwidth=4
set nu
set ai
syntax on
filetype plugin indent on
I tried this, content.gsub("\r\n","<br/>") but when I click the view/show button to see the contents of these line, I get the output/result=>
set tabstop=4<br/> set shiftwidth=4<br/> set nu<br/> set ai<br/> syntax on<br/> filetype plugin indent on
But I tried to get those lines as a seperate lines. But all become as a single line. Why?
How can I make all those lines with a html break (<br/>) ?
I tried this, that didn't work.
#addpost = Post.new params[:data]
#temptest = #addpost.content.html_safe
#addpost.content = #temptest
#logger.debug(#addpost)
#addpost.save
Also tried without saving into database. Tried only in view layer,<%= t.content.html_safe %> That didn't work too.
Got this from page source
vimrc file <br/>
2011-12-06<br/><br/>
set tabstop=4<br/><br/>set shiftwidth=4<br/><br/>set nu<br/><br/>set ai<br/><br/>syntax on<br/><br/>filetype plugin indent on<br/>
Edit
Delete
<br/><br/>
An alternative to convert every new lines to html tags <br> would be to use css to display the content as it was given :
.wrapped-text {
white-space: pre-wrap;
}
This will wrap the content on a new line, without altering its current form.
You need to use html_safe if you want to render embedded HTML:
<%= #the_string.html_safe %>
If it might be nil, raw(#the_string) won't throw an exception. I'm a bit ambivalent about raw; I almost never try to display a string that might be nil.
With Ruby On Rails 4.0.1 comes the simple_format from TextHelper. It will handle more tags than the OP requested, but will filter malicious tags from the content (sanitize).
simple_format(t.content)
Reference : http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html
http://www.ruby-doc.org/core-1.9.3/String.html
as it says there gsub expects regex and replacement
since "\n\r" is a string you can see in the docs:
if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. '\d' will match a backlash followed by ā€˜dā€™, instead of a digit.
so you are trying to match "\n\r", you probably want a character class containing \n or \r -[\n\r]
a = <<-EOL
set tabstop=4
set shiftwidth=4
set nu
set ai
syntax on
filetype plugin indent on
EOL
print a.gsub(/[\n\r]/,"<br/>\n");
I'm not sure I exactly follow the question - are you seeing the output as e.g. preformatted text, or does the source HTML have those tags? If the source HTML has those tags, they should appear on new lines, even if they aren't on line breaks in the source, right?
Anyway, I'm guessing you're dealing with automatic string escaping. Check out this other Stack Overflow question
Also, this: Katz talking about this feature

I'm new to Perl and have a few regex questions

I'm teaching myself Perl and I learn best by example. As such, I'm studying a simple Perl script that scrapes a specific blog and have found myself confused about a couple of the regex statements. The script looks for the following chunks of html:
<dt><a name="2004-10-25"><strong>October 25th</strong></a></dt>
<dd>
<p>
[Content]
</p>
</dd>
... and so on.
and here's the example script I'm studying:
#!/usr/bin/perl -w
use strict;
use XML::RSS;
use LWP::Simple;
use HTML::Entities;
my $rss = new XML::RSS (version => '1.0');
my $url = "http://www.linux.org.uk/~telsa/Diary/diary.html";
my $page = get($url);
$rss->channel(title => "The more accurate diary. Really.",
link => $url,
description => "Telsa's diary of life with a hacker:"
. " the current ramblings");
foreach (split ('<dt>', $page))
{
if (/<a\sname="
([^"]*) # Anchor name
">
<strong>
([^>]*) # Post title
<\/strong><\/a><\/dt>\s*<dd>
(.*) # Body of post
<\/dd>/six)
{
$rss->add_item(title => $2,
link => "$url#$1",
description => encode_entities($3));
}
}
If you have a moment to better help me understand, my questions are:
how does the following line work:
([^"]*) # Anchor name
how does the following line work:
([^>]*) # Post title
what does the "six" mean in the following line:
</dd>/six)
Thanks so much in advance for all your help! I'm also researching the answers to my own questions at the moment, but was hoping someone could give me a boost!
how does the following line work...
([^"]*) # Anchor name
zero or more things which aren't ", captured as $1, $2, or whatever, depending on the number of brackets ( in we are.
how does the following line work...
([^>]*) # Post title
zero or more things which aren't >, captured as $1, $2, or whatever.
what does the "six" mean in the
following line...
</dd>/six)
s = match as single line (this just means that "." matches everything, including \n, which it would not do otherwise)
i = match case insensitive
x = ignore whitespace in regex.
x also makes it possible to put comments into the regex itself, so the things like # Post title there are just comments.
See perldoc perlre for more / better information. The link is for Perl 5.10. If you don't have Perl 5.10 you should look at the perlre document for your version of Perl instead.
[^"]* means "any string of zero or more characters that doesn't contain a quotation mark". This is surrounded by quotes making forming a quoted string, the kind that follows <a name=
[^>]* is similar to the above, it means any string that doesn't contain >. Note here that you probably mean [^<], to match until the opening < for the next tag, not including the actual opening.
that's a collection of php specific regexp flags. I know i means case insensitive, not sure about the rest.
The code is an extended regex. It allows you to put whitespace and comments in your regexes. See perldoc perlre and perlretut. Otherwise like normal.
Same.
The characters are regex modifiers.