what is {VARIABLE} in HTML means, and how to initialize it? - php

I have recently reading someone code. In his code I see a weird html text written like {VARIABLE} . What is that syntax mean? and how to create it? Thanks

In PHP, there's something called "Complex (curly) syntax" (look for this deeper in the page) where you inject variable's values into strings using {} instead of cutting and concatenating the string.
A similar answer can be found here
Another case is that the HTML could contain that text is when it is used as a template, like this one in CodeIgniter.

You don't initialize it. It's part of their templating engine.
Regardless of how they are doing it, the idea is to find/replace "{VAR}" with the actual data you want.
var songTemplate = "<li class=\"track\"><span class=\"num\">{{TRACKNUM}}.</span>" +
"<span class=\"title\">{{TITLE}}</span>" +
"<span class=\"duration\">{{DURATION}}</span></li>";
var songs = [ { tracknum : 1, title : "Speak to Me/Breathe", duration : "4:13" },
{ tracknum : 2, title : "On the Run", duration : "3:36" },
{ tracknum : 3, title : "Time", duration : "7:01" } ];
function makeTrack (song, template) {
var track = "";
track = template.replace("{{TRACKNUM}}", song.tracknum);
track = template.replace("{{TITLE}}"), song.title);
track = template.replace("{{DURATION}}", song.duration);
return track;
}
function trackList (songs, template) {
var list = "<ul class=\"tracklist\">";
songs.forEach(function (song) {
list += makeTrack(song, template);
});
list += "</ul>";
return list;
}
var songlist = trackList(songs, songTemplate);
parentEl.innerHTML = songlist;
The basic idea, regardless of what language is used to template it, is that you start with a string of HTML, pull out what you know you want to replace, and put in the data that you want.
I've shown you an ugly, ugly template (it'd be better if I only had to write in an array of variable names, and it did the rest... ...or if it looked through the string to find {{X}} and then looked through an object for the right value to replace what it found).
This also has security holes, if you don't control both the template and the data (if you allow for end-user input anywhere on your site, then you don't have control).
But this should be enough to show how templates do what they do, and why.

Related

Retrieve HTML from database, and format it as html instead of plain text

I have a database query that returns the raw HTML for a page, but if I use it on my page, it gets shown as plain text (of course). How would I format it as HTML so that it uses the tags and such.
An example of what I have in my database:
<div class="test">SOME TEXT HERE</div>
But it is also displayed like that. I would like it to format the text as if it was HTML. So it would just display:
SOME TEXT HERE
But that it would also be in a div with the class: "test"
What would be the best approach to reach this goal?
Im using Twig in the MVC model to render the page. So the page renderer is like this
public function renderArticle() {
$twig = new TwigHelper();
$args['title'] = "Artikel $this->articleId";
$args['blogHTML'] = BlogController::retrieveBlogHTML($this->articleId);
echo $twig->render('article.twig', $args);
}
And the "BlogController::retrieveBlogHTML" goes like this:
public static function retrieveBlogHTML($id) {
$db = DatabaseHelper::get();
$st = $db->prepare("SELECT PageHTML FROM T_Blog WHERE BlogId = :BlogId");
$st->execute([
':BlogId' => $id,
]);
if ($st->errorCode() !== \PDO::ERR_NONE) {
return null;
}
return $st->fetchAll();
}
This means that I will not be able to use JavaScript at this point in time, if that will be the only way to fix the problem i'll have to build a workaround.
So I dont know if I accidently escape too or something along those lines, but im not using any headers.
You need to escape the html characters (so < becomes < for example).
In javascript you can use the HE library or theres this function, which is generally fine, but doesn't cover all possible cases that the HE library does
var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
If your using php you can use htmlentities, other languages will have a similar function either inbuilt or provided via a library.

Copying a Word and saving it as a Variable

I am building an online spanish dictionary. I obtain the definitions legally from another site. For specific words the user may search for, a list of suggestions comes up.
If you click on any of those suggested words, error page pops up: http://verbum.xtrweb.com/verbumpost.php?word=boedo&word0=hola . How can I make those listed words run through the code pasted below: (1) retrieve definition (2) change style.
I know that a unique URL exists for every one of those suggested words (inspect element). If you paste together that code with the original site's URL parameters, you get what I need.:
"http://lema.rae.es/drae/srv/search?id=AVNYdnea1DXX2EH9E2mb"
up to "srv/" belongs to site
the rest is from the specific word (in this case, the first suggested, "bordar"
The Process:
<?php
$words = array('word','word0','word1','word2','word3','word4','word5','word6','word7','word7','word9',
'word10','word11','word12',
'word13','word14','word15');
function url_decode($string){
return urldecode(utf8_decode($string));
}
// we'll use this later on for loading the files.
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
// string to replace in the head.
$cssReplace = <<<EOT
<style type="text/css">
//blabla
</style>
</head>
EOT;
// string to remove in the document.
$spanRemove = '<span class="f"><b>.</b></span>';
$styleRemove =
// use for printing out the result ID.
$resultIndex = 0;
// loop through the words we defined above
// load the respective file, and print it out.
foreach($words as $word) {
// check if the request with
// the given word exists. If not,
// continue to the next word
if(!isset($_REQUEST[$word]))
continue;
// load the contents of the base url and requested word.
$contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));
// replace the data defined above.
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = str_replace($spanRemove,"", $contents);
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $data);
// print out the result with the result index.
// ++$resultIndex simply returns the value of
// $resultIndex after adding one to it.
echo "<div id='results' style='
//bla bla
}
?>
I don't think I understand your question, but I do see that you are calling preg_replace on an uninitialized variable - $data.
Maybe you want this instead?
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $contents);
Like I said, I don't fully understand your question, but I do see that as a potential problem.
EDIT:
From your comment, it looks like you want to append the href of the link being clicked to a base url and request that page's data. Can you use jQuery? Like this:
var baseUrl = "http://lema.rae.es/drae/srv/"; // base url
//click function that binds to all anchors within a list item within a ul. in order
//to get more precise, you may need to add some classes or ids
$('ul li a').click(function(){
var src = $(this).prop('href'); //this grabs the href property of the anchor
$(this).find('span').css('propery', 'change to this'); //change css property of span child of this anchor
//or if you want to add a class with styles to the element
$(this).find('span').addClass('class name');
//ajax request to get page data
$.ajax({
type: 'POST',
url: baseUrl+src //appending the query to the base url
}).done(function(data){
//append the returned html to a div, or any element you desire
$('#myelement').append(data);
});
});
Hope this helps. If you need any help with jQuery just let me know.

Pagination: How to display a long text as book pages?

I have a very long text and I want to display it as a book in a web page. The user will use arrow keys to move forward and backward in same way like flipping pages of the book.
Leaving apart the transition of pages, how can this be achieved using jQuery?
What I thought was calculating the amount of text that will occupy the space on one page and then breaking the whole text into such pages and then displaying them. But it seems to be a bad idea for the space occupied will be platform dependent even if we fix the font.
One more problem that I was facing while using the space calculation method was due to the css justified display of text.
Has anyone done such thing before for a web page?
To layout a long string in a beautiful book page format. You need to get the exact string portion. You can use this function.
function get_page($text, $page_index, $line_length=76, $page_length=40){
$lines = explode("\n", wordwrap($texxt, $line_length, "\n"));
$page_lines = array_slice($lines, $page_index*$page_length, $page_length);
return implode("\n", $page_lines);
}
$line_length = 70;
$lines_per_page=50;
$page = 3;
$longtext= "...";
$page_text = get_page($longtext, $page-1, $line_length, $page_length);
See Demonstration.
Example
PHP
$longtext = "..."; // it can be retrieved from sql as well.
$index=is_int($_GET['page'])? intval($_GET['page']): 1;
$line_length = 70;
$lines_per_page=50;
$longtext= "...";
$page_text = get_page($longtext, $index-1, $line_length, $page_length);
echo json_encode(array('text'=>$page_text));
JQuery
var nextPage=2;
$.get("getpage.php", { page: nextPage }, function(data){
alert("text is "+data.text;
// show the text data.text
});

PHP javascript call with PHP variable

Good day, I am having a very odd error with my PHP code. I am attempting to dynamically change the content of my webpage by reading from an xml file. I read in some data and assign the data to a PHP variable called $course_title and then attempt to call some Javascript that will update the "innerHTML" of a DOM element. Note: on the line "echo $course_title;' that prints out the correct data to the screen.
$fn = dirname(__FILE__)."/course.xml";
$xml = simplexml_load_file($fn);
$course_bookimagelocation = "";
foreach ($xml->children() as $child)
{
if($child[0]->getName()=="book")
$course_bookimagelocation = $child;
if($child[0]->getName()=="title")
$course_title = $child;
}
//Problems start here...
echo $course_title;
echo '<script type="text/javascript">document.getElementById("heading").innerHTML = "';
echo $course_title;
echo '";</script>';
What is very unique is that the first echo statement prints the correct information, but the next three lines, the .innerHTML does not get changed to that same value. Does anyone know what that is? What is also weird is that if I replace the second "echo '$course_title';" with something like 'Hello world!' then "Hello World!" appears as the innerHTML of the "heading" id object.
EDIT
In the XML file called course.xml, the title element is IC 210 Fall 2010 and the contents of $course_title is IC 210 Fall 2010 so the parsing of the php file appears to be correct and there does not seam to be any special characters like a " or '
I also tried putting everything on the same line and not luck... (I even made sure in the xml file that the <title> element had the text on the same line...
Make sure that .innerHTML = "Some text" are on the same line because .innerHTML = "\nSome Text\n" won't work in javascript.
If you want to have something like this:
.innerHTML = "
Some String
";
try:
.innerHTML = ""+
"Some String" +
"";
"call some Javascript that will update the "innerHTML" of a DOM element." for that we use AJAX, no?
well you can do that way but i think it would be simpler to have the text preloaded in some hidden DIV's and use your functions just to change content's of the DIVS or even toggle visibility of the DIV (as you prefer). That way you will avoid many escaping problem's referred in the comments.
that's the way i would do it if not to use AJAX

JavaScript regular expression to replace HTML anchors

I got a HTML string and from this I want to convert some special a tags to something else. I need this for a TinyMCE plugin. I tried to change Wordpress wpgallery plugin.
For example: These are in HTML string
Yahoo
Google
<a href="#" rel='special' title='link cat_id="4" content_id="5" content_slug="Slug 1"'>Some where else</a>
Here I have to find special link one and convert it to something else from it's title value
like:
{link cat_id="4" content_id="5" content_slug="Slug 1"}
i need return value like this to insert it into MySQL
Yahoo
Google
{link cat_id="4" content_id="5" content_slug="Slug 1"}
I tried this
function getAttr(s, n) {
n = new RegExp(n + '="([^"]+)"', 'g').exec(s);
return n ? tinymce.DOM.decode(n[1]) : '';
};
return co.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function(a,im) {
var cls = getAttr(im, 'rel');
if ( cls.indexOf('special') != -1 )
return '{'+tinymce.trim(getAttr(im, 'title'))+'}';
return a;
});
this
/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g
does not find tags with rel eq to 'special' but all the others.
You might want to look into the DOMDocument and related classes. They are much better at parsing HTML than a homebrewed regex solution would be.
You can create a DOMdocument using your supplied markup, execute getElementsByTagName to get all the hyperlinks, scan their attributes for a rel attribute with the value of special, and then take the appropriate action.

Categories