Possible for Blade not to escape certain html tags? - laravel-5.1

In Laravel Blade, {{...}} will escape all HTML tags.
Is it possible to exclude certain tags from being escaped, such as <p> or <br/>? While I can just {!!...!!}}, it will allow any tags to be displayed.

you should go to
vendor\laravel\framework\src\Illuminate\View\Compilers\BladeCompiler.php
and chang this function
protected function compileRawEchos($value)
{
$pattern = sprintf('/(#)?%s\s*(.+?)\s*%s(\r?\n)?/s', $this->rawTags[0], $this->rawTags[1]);
$callback = function ($matches) {
$whitespace = empty($matches[3]) ? '' : $matches[3].$matches[3];
return $matches[1] ? substr($matches[0], 1) : '<?php echo '.$this->compileEchoDefaults($matches[2]).'; ?>'.$whitespace;
};
return preg_replace_callback($pattern, $callback, $value);
}

Related

DOMDocument - How to get all inner text except from style/script tags?

I spent so much time on a very simple thing and had to post here on StackOverflow
I want to get all inner text except the script/style tags
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$html = <<<EOD
<div>
<script>var main=0</script>
<div>
<p>my</p>
<script>var inner=0</script>
</div>
<p>text</p>
only
</div>
EOD;
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
echo $entries = $xpath->query('//*[not(self::script)]')->item(0)->nodeValue;
gives me
var main=0 my var inner=0 text only
and also tried
$entries = $xpath->query('//*[not(self::script)]');
foreach ($entries as $entry) {
if ($entry->tagName == 'style' || $entry->tagName == 'script') {
continue;
}
echo preg_replace('/\s\s+/', ' ', $entry->nodeValue);
}
gives me
var main=0 my var inner=0 text only var main=0 my var inner=0 text only var main=0 my var inner=0 text only my var inner=0mytext
I tried several xpaths but it doesn't work
my desired output is my text only
I am a Scrapy developer and I do that easily in Scrapy, but having a bad time with PHP today
Unfortunately, PHP doesn't support xpath 2.0 (and, IIRC, neither does Scrapy), so the name() method which would have made it easy, isn't available...
The closest thing I can think of is the following, which should get you close enough (note that, because there is no <style> tag in your $html, I only focused on <script>):
$entries = $xpath->query('//*[not(./text()/parent::script)]/text()');
foreach ($entries as $entry) {
echo trim($entry->textContent) . " ";
}
Output:
my text only

iOS 11 Safari HTML - Disable "Smart Punctuation"?

Is there a good way to disable the "Smart Punctuation" the iOS 11 Apple Keyboard generates - in Safari on an HTML login form - username field in particular?
The problem is that we have users with apostrophes in their usernames. Typing their usernames on iOS 11 and not knowing the subtleties of unicode they are not able to sign in.
Ideally we could just instruct such users to disable smart quotes or type the proper character by holding down the apostrophe key - but I am working on educational software for small children and that is out of the question.
The problem is compounded by the fact that there are also a small selection of users with actual curly single quotes in their usernames, so a simple map of replacements won't work - and we can't canonicalize the usernames as they come from a number of external systems we don't control / can't have a lot of say over.
Unfortunately according to this MDN page there is no known Webkit <input> or <textarea> attributes to disable smart-quotes, but you can patch it with a script I've written derived from this QA: How to disable smart quotes for textarea fields in the browser?
window.addEventListener('DOMContentLoaded', attachFilterToInputs );
function attachFilterToInputs() {
var textInputs = document.querySelectorAll( 'input[type=text], input[type=password], input[type=email], input[type=search], input[type=url], textarea, *[contenteditable=true]' );
for( var i = 0; i < textInputs.length; i++ ) {
textInputs[i].addEventListener( 'keypress', preventPretentiousPunctuation );
}
}
var conversionMap = createConversionMap();
function createConversionMap() {
var map = {};
// Open-quotes: http://www.fileformat.info/info/unicode/category/Pi/list.htm
map[ 0x2018 ] = '\'';
map[ 0x201B ] = '\'';
map[ 0x201C ] = '"';
map[ 0x201F ] = '"';
// Close-quotes: http://www.fileformat.info/info/unicode/category/Pf/list.htm
map[ 0x2019 ] = '\'';
map[ 0x201D ] = '\"';
// Primes: http://www.fileformat.info/info/unicode/category/Po/list.htm
map[ 0x2032 ] = '\'';
map[ 0x2033 ] = '"';
map[ 0x2035 ] = '\'';
map[ 0x2036 ] = '"';
map[ 0x2014 ] = '-'; // iOS 11 also replaces dashes with em-dash
map[ 0x2013 ] = '-'; // and "--" with en-dash
return map;
}
function preventPretentiousPunctuation( event ) {
if( event.key.length != 1 ) return;
var code = event.key.codePointAt(0);
var replacement = conversionMap[ code ];
if( replacement ) {
event.preventDefault();
document.execCommand( 'insertText', 0, replacement );
}
}
Thanks to Dai for the outline of the answer. Unfortunately when we implemented their solution and tested on an iOS 11 device, we found that the keypress event listener wasn't firing at all. We reworked their solution using the input event and regex string replace and found this did work for us.
Here is our variation, using jQuery for the selector and a shorter replace list.
<script type="text/javascript">
// Here are the reference to Unicode Characters in the Punctuation
// Open-quotes: http://www.fileformat.info/info/unicode/category/Pi/list.htm
// Close-quotes: http://www.fileformat.info/info/unicode/category/Pf/list.htm
window.addEventListener('DOMContentLoaded', attachFilterToInputs);
// Patch the iOS Smart Punctuation functionality on restricted field(s),
// so that the user types acceptable characters.
function attachFilterToInputs() {
try {
$("[name$='MyProtectedFieldName']").on('input', preventPretentiousPunctuation);
}
catch (err) {
// do nothing
}
}
function preventPretentiousPunctuation(event) {
try {
var str = $(this).val();
var replacedStr = "";
replacedStr = str.replace(/[\u2018\u2019\u201C\u201D]/g,
(c) => '\'\'""'.substr('\u2018\u2019\u201C\u201D'.indexOf(c), 1));
if (str !== replacedStr) {
$(this).val(replacedStr);
}
}
catch (err) {
// do nothing
}
}
</script>
Adding as an answer since I don't have the rep to comment.

Get code between tags and generate youtube embed

I have some tekst and in the middle of article I put {youtube}IPtv14q9ZDg{/youtube}. How to make code which is between {youtube} generated in youtube embed
I use PHP, but there might be other options.
I filter the text for the key-words. Then take the 11 digit code and wrap it in a link tag. Works best in a "for loop".
This is one I use to find url's in my text and make them live. But you can modify it to do what you want by changing the "preg_match" setting.
function make_clickable($string) {
$string = preg_replace("/[\n\r]/"," <br /> ",$string);
$arr = explode(' ', $string);
foreach($arr as $key => $value){
if(preg_match('#((^https?|http|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i', $value)){
$arr[$key] = "<a class=\"custome\" href='". $value ."' target=\"_blank\" class='link'>$value</a> ";
}
}
$string = implode(' ', $arr);
return $string;
}

.net Razor alternative to PHP echo

I'm new to .net MVC and Razor engine but I have been using PHP for a long time. I'm trying to do this PHP code in Razor:
var data = [
<?php for ($i = 0; $i < 50; ++$i) {
echo '[' . $i . ',' . sin($i) . ']';
if ($i != 49)
echo ',';
?>
],
I managed to do it using this, but it looks bad and complex for something so simple
var data = [
#for(int i = 0; i < 50; ++i) {
<text>[</text>#i<text>,</text>#Math.Sin(i)<text>]</text>if (i != 49) {<text>,</text>}
}
];
The problem is that [, ] and , are confused with Razor syntax and gives syntax errors, so I had to wrap them on <text> tags.
Is there a simpler/nicer way to do this? Maybe something like the PHP echo.
Thanks.
A gerenal equivalent of echo in MVC cshtml might be:
#Html.Raw("SomeStringDirectlyInsideTheBrowserPageHTMLCode")
This renders the (dynamic) string at its position where '<' and '>' no need to be HTML-coded. For example #Html.Raw(String.Format("<div class=\"{0}\" style=\"{1}\">", myclass, mystyle)) works fine.
Note that the HTML tags rendered by #Html.Raw(MyString) cannot be checked by the compiler. I mean: #Html.Raw("<div ....>") cannot be closed by mere </div> because you will get an error (<div ....> is not detected by the compiler) so you must close the tag with #Html.Raw("</div>")
P.S.In some cases this doesn't work (for example it fails within DevExpress) - use ViewContext.Writer.Write() or ViewContext.Writer.WriteLine() instead.
Use this:
#String.Format("[{0},{1}]", i, Math.Sin(i))
And for comma you can use String.Join() if you create array (String.Join Method )
Old question I know, but an alternative is to use the plaintext syntax #:
var data = [
#for (int i = 0; i < 50; ++i)
{
#:[#i,#Math.Sin(i)]
#(i != 49 ? "," : "")
}
];
Constructing a JSON object using a view is not really the best way to go about it. You can use the native JSON support to do this directly from a controller, for example:
public JsonResult SinArray()
{
return new JsonResult() {
Data = Enumerable.Range(0, 50).Select(i => new[] { i, Math.Sin(i) }),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
This returns
[[0,0],[1,0.8414709848078965],[2,0.90929742682568171],.....,[49,-0.95375265275947185]]
As a bonus you get the correct content-type.

How to parse Markdown in PHP?

First, I know, there already is a Markdown parser for PHP.
I also took a look to this question but it doesn't answer to my question.
Obviously, even if the title mention PHP, if it's language agnostic, because I'd like to know what are the step I've to go through to do that.
I've read about PEG, but I've to admit, I didn't really understand the example provided with the PHP parser.
I've also read about CFG.
I've found Zend_Markup_Parser_Textile which seems to construct a so called "Token Tree" (what's about it?) but it currently unusable. (Btw, Textile is not Markdown)
So, concretely, how would you go to this?
Obviously I though about using Regex but, I'm afraid.
Because Markdown supports several syntaxes for the same element (Setext and atx).
Could you give some starting point?
You should have a look at Parsedown.
It parses Markdown text the way people do. First, it divides texts into lines. Then it looks at how these lines start and relate to each other. Finally, it looks for special characters to identify inline elements.
There is PHP Markdown Extra that seems to be popular, you could start by looking at its source.
Also, there is an object-oriented implementation of Markdown which is faster: markdown-oo-php
Ciconia - A New Markdown Parser for PHP is a good one I found.
You just need 3 things to do :
1.Install Ciconia and parse file according to the document.
2. Add corresponding css theme to make it nice, like github markdown style or here.
3. Add syntax highlighting javascript, like google Javascript code prettifier.
Then everything will look pretty good.
If you want a complete example, here is my working demo for github style markdown:
<?php
header("Content-Type: text/html;charset=utf-8");
require 'vendor/autoload.php';
use Ciconia\Ciconia;
use Ciconia\Extension\Gfm;
$ciconia = new Ciconia();
$ciconia->addExtension(new Gfm\FencedCodeBlockExtension());
$ciconia->addExtension(new Gfm\TaskListExtension());
$ciconia->addExtension(new Gfm\InlineStyleExtension());
$ciconia->addExtension(new Gfm\WhiteSpaceExtension());
$ciconia->addExtension(new Gfm\TableExtension());
$ciconia->addExtension(new Gfm\UrlAutoLinkExtension());
$contents = file_get_contents('Readme.md');
$html = $ciconia->render($contents);
?>
<!DOCTYPE html>
<html>
<head>
<title>Excel to Lua table - Readme</title>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
<link rel="stylesheet" href="./github-markdown.css">
<style>
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
</style>
</head>
<body>
<article class="markdown-body">
<?php
# Put HTML content in the document
echo $html;
?>
</article>
</body>
</html>
Using regexes.
<?php
/**
* Slimdown - A very basic regex-based Markdown parser. Supports the
* following elements (and can be extended via Slimdown::add_rule()):
*
* - Headers
* - Links
* - Bold
* - Emphasis
* - Deletions
* - Quotes
* - Inline code
* - Blockquotes
* - Ordered/unordered lists
* - Horizontal rules
*
* Author: Johnny Broadway <johnny#johnnybroadway.com>
* Website: https://gist.github.com/jbroadway/2836900
* License: MIT
*/
class Slimdown {
public static $rules = array (
'/(#+)(.*)/' => 'self::header', // headers
'/\[([^\[]+)\]\(([^\)]+)\)/' => '<a href=\'\2\'>\1</a>', // links
'/(\*\*|__)(.*?)\1/' => '<strong>\2</strong>', // bold
'/(\*|_)(.*?)\1/' => '<em>\2</em>', // emphasis
'/\~\~(.*?)\~\~/' => '<del>\1</del>', // del
'/\:\"(.*?)\"\:/' => '<q>\1</q>', // quote
'/`(.*?)`/' => '<code>\1</code>', // inline code
'/\n\*(.*)/' => 'self::ul_list', // ul lists
'/\n[0-9]+\.(.*)/' => 'self::ol_list', // ol lists
'/\n(>|\>)(.*)/' => 'self::blockquote ', // blockquotes
'/\n-{5,}/' => "\n<hr />", // horizontal rule
'/\n([^\n]+)\n/' => 'self::para', // add paragraphs
'/<\/ul>\s?<ul>/' => '', // fix extra ul
'/<\/ol>\s?<ol>/' => '', // fix extra ol
'/<\/blockquote><blockquote>/' => "\n" // fix extra blockquote
);
private static function para ($regs) {
$line = $regs[1];
$trimmed = trim ($line);
if (preg_match ('/^<\/?(ul|ol|li|h|p|bl)/', $trimmed)) {
return "\n" . $line . "\n";
}
return sprintf ("\n<p>%s</p>\n", $trimmed);
}
private static function ul_list ($regs) {
$item = $regs[1];
return sprintf ("\n<ul>\n\t<li>%s</li>\n</ul>", trim ($item));
}
private static function ol_list ($regs) {
$item = $regs[1];
return sprintf ("\n<ol>\n\t<li>%s</li>\n</ol>", trim ($item));
}
private static function blockquote ($regs) {
$item = $regs[2];
return sprintf ("\n<blockquote>%s</blockquote>", trim ($item));
}
private static function header ($regs) {
list ($tmp, $chars, $header) = $regs;
$level = strlen ($chars);
return sprintf ('<h%d>%s</h%d>', $level, trim ($header), $level);
}
/**
* Add a rule.
*/
public static function add_rule ($regex, $replacement) {
self::$rules[$regex] = $replacement;
}
/**
* Render some Markdown into HTML.
*/
public static function render ($text) {
$text = "\n" . $text . "\n";
foreach (self::$rules as $regex => $replacement) {
if (is_callable ( $replacement)) {
$text = preg_replace_callback ($regex, $replacement, $text);
} else {
$text = preg_replace ($regex, $replacement, $text);
}
}
return trim ($text);
}
}
echo Slimdown::render ("# Title
And *now* [a link](http://www.google.com) to **follow** and [another](http://yahoo.com/).
* One
* Two
* Three
## Subhead
One **two** three **four** five.
One __two__ three _four_ five __six__ seven _eight_.
1. One
2. Two
3. Three
More text with `inline($code)` sample.
> A block quote
> across two lines.
More text...");
Origin https://gist.github.com/jbroadway/2836900

Resources