Is it possible? If so, how?
If its not, do I have to abandon pug if I need to write PHP in my documents?
After searching around I didnt find anyone that has adressed this.
You can embed PHP in Pug templates the same way you would any literal plain text that you want passed through relatively unmolested[*]. There are a number of options covered in the docs, but I think these are most likely the best options for embedding PHP:
After an element, it will just work. For example, p Good morning, <?php echo $user->name ?>.
On a single line by itself. Since any line beginning with "<" is passed as plain text, any one line PHP statement (e.g., <?php echo $foo; ?>) will just work.
Multi-line PHP is the one case where it gets a bit complicated. If you're ok with wrapping it in an HTML element, you can use Pug's block text syntax: Put a dot after the element, then include your plain text indented underneath.
p.
<?php
if ($multiline) {
echo 'Foo!';
}
?>
If you need it outside an element, the other option is to prefix every line with a pipe:
|<?php
|if ($multiline) {
| echo 'Foo!';
|}
|?>
(Technically, the first line doesn't need to be prefixed due to point 2 above, but if using this method I would prefix it anyway just for consistency.)
To use PHP in attributes, you just need to prevent escaping by prefixing the equals sign with a bang: p(class!="<?php echo $foo ?>"). (Interestingly, support for unescaped attribute values was added specifically for this use case.)
Of course by default .pug files are compiled to .html files, so if you're using them to generate PHP, you'll want to change the extension. One easy way to do this is to process them using gulp with the gulp-pug and gulp-rename plugins, which would look something like this:
var gulp = require('gulp'),
pug = require('gulp-pug'),
rename = require('gulp-rename');
gulp.task('default', function () {
return gulp.src('./*.pug')
.pipe(pug())
.pipe(rename({
extname: '.php'
}))
.pipe(gulp.dest('.'));
});
I haven't worked extensively with Pug, so I don't know if there are any potential gotchas that would come up in real world use cases, but the simple examples above all work as expected.
[*] Pug still performs variable interpolation on plain text, but it uses the #{variable} format, which should not conflict with anything in PHP's standard syntax.
Since PHP doesn't care whether the "outside" code is HTML or really anything specific, you could simply use PHP as you normally would and have it output Pug-formatted code instead of HTML. For instance:
myPugTemplate.pug.php
html
head
title "<?= $this->title ?>"
body
<?php
// Since we're outputing Pug markup, we have to take care of
// preserving indentation.
$indent=str_repeat(' ', 2);
if ($this->foo) {
echo $indent . 'bar= myPost';
} else {
echo $indent . 'baz= myNav';
}
?>
footer
+footerContent
And if your Pug is processed on the server then you'd also include a Pug-processing step, for instance if you use Apache you could use
mod_ext_filter configured in such fashion with pug-cli installed:
ExtFilterDefine pug-to-html mode=output intype=text/pug outtype=text/html \
cmd="pug"
<Location />
SetOutputFilter pug-to-html
</Location>
Have you checked out the pug-php project? I personally have no experience with this particular module, but it seems to do just what you're trying to accomplish: Being able to use PHP in Pug.
You can use the scape syntax with quotes:
!{'<?php #php code ?>'}
For example:
p Hello !{'<?php echo "My name"; ?>'}
Will render:
<p>Hello <?php echo "My name"; ?></p>
You can test it here: https://pug-demo.herokuapp.com/
There is a well-known and well-maintained Pug processor written natively in PHP. You can use it to process your Pug files into HTML, just like the original Pug, with the advantage that it allows you to embed and use PHP code in your Pug file with ease. If you're working with PHP inside Pug, check it out:
Phug - the Pug template engine for PHP
p Hello !{'<?php echo "My name"; ?>'}
works but
link(href="../assets/css/style.css?v=!{'<?=$AppsVersion?>'}" rel="stylesheet" type="text/css")
don't work
Related
This question already has answers here:
Is there harm in outputting html vs. using echo?
(4 answers)
Closed 5 years ago.
Is there a difference between this
<?php
myCode();
echo "Example";
?>
and
<?php
myCode();
?>
Example
this?
What is the best choice in terms of performance?
I've done a Benchmark printing 20000000 times "Example". I've executed the script from CLI, not through HTTP request (Centos 7 64bit).
Using "echo": 153.06723901367sec
Using HTML: 155.80555395508sec
For all pragmatic purposes, no, there is no relevant difference. Your script output will be "Example" in both cases. And in both cases, myCode() was executed before.
In fact, the OPCodes in both cases will be the same, because PHP will echo everything outside of <?php tags. It's basically just an implicit echo.
Technically, the way to the resulting OPCodes will be different, but this has no relevant impact on performance. Mostly anything outside <?php tags is treated as T_INLINE_HTML by the parser. This is then converted to an echo in the abstract syntax tree:
| T_INLINE_HTML { $$ = zend_ast_create(ZEND_AST_ECHO, $1); }
with ZEND_AST_ECHO being
case ZEND_AST_ECHO:
APPEND_NODE_1("echo");
However, your aim should be to separate logic from your views and templates as good as possible as it can easily lead to spaghetti code if you don't. As a rule of thumb, a function should not echo, but return strings. Most frameworks only echo once: at the end of a request when rendering the response.
Since you mentioned "Views" and MVC: a View in MVC is not necessarily a template, but a specific representation of a particular piece of data from the Model. It can be code that ultimately renders a template though. If that's what you want, you probably want to check out a template engine, like Twig (although PHP is a template engine on it's own).
Yes. The 1st is PHP, the 2nd is HTML.
In the first case you could do:
<?php
$var = 1;
echo "Example " . $var;
?>
The second case $var is undefined in the HTML so would be ignored.
<?php
$var = 1;
?>
Example $var
If you wanted to use that variable in the HTML you would need to go back into PHP i.e.
<?php echo $var; ?>
This is a preference thing in my experience, there are some pages that are mostly HTML that can be written that way. However, if I am writing PHP I prefer to stick with PHP and not bounce between the 2 languages. I don't know of anything that you can do in HTML that you can't produce from PHP. It makes for nasty looking code that is hard to debug.
Also there are issues with HTML headers (see PHP header() Function).
Ay guys,
I do know two possibilites to display PHP in HTML:
<?php function(); ?> or the shorter method <?= function(); ?>
But I often see something like {METHOD} or {OUTPUT} in the HTML part of bigger scripts f.e.:
<div class="test">{OUTPUT}</div>
In my opinion this is a way tidier. Could somebody tell me more about this?
I have used php to generate html using the echo function and have used php inside html too.(If this clarifies your doubt in anyway)
echo $projectname; inside html file tags
echo the html file
Cheers :)
When echoing data in HTML without a template engine, short tags are preferred as they look cleaner, and are easier to read. They're great when using control structures too: http://php.net/manual/en/control-structures.alternative-syntax.php
For short tags to work short_open_tag needs to be enabled.
The example you shown with the curly brackets is usually specific to a template engine such as Twig.
you can use this method only with the function ECHO with double quotes :
1 - this works
$name = 'Mark';
echo "<div>GoodMorning {$name}</div>";
2 - this does not work
$name = 'Mark';
echo '<div>GoodMorning {$name}</div>';
I'm looking for something that Is really hard for me to do.. I really tried to search all over the net for Solution, But I couldn't seem to find any. I also tried doing this for hours.
What I'm doing: Making a theme for PHPBB2, Installed a MOD that can include PHP in themes.
What is the problem: When I'm doing {} tags in php, It just can't echo those tags.
Let's say I have a function that creates a Table for me, like that:
CreateMyTable(Name,Size,Color);
I put in the function those strings:
CreateMyTable("{FORUM_NAME}",1000,red);
The title stays blank, I actually want it to echo {FORUM_NAME}.
How can I do this?
P.S: I can't do this
CreateMyTable(?>{FORUM_NAME}<?php , 1000, red);
It's not going to work becuase <? = <!-- PHP --> , ?> = <!-- ENDPHP -->.
Thanks for your help :)
If you look in the PHPbb2 template class, you'll find that the template is simply an evaluated set of PHP using the eval() function. You can either print the contents of the PHP before it is parsed using eval() and then use the variable name that the template gives, IE something like (which may not work depending how your template is setup):
CreateMyTable(((isset($this->_tpldata['.'][0]['FORUM_NAME'])) ? $this->_tpldata['.'][0]['FORUM_NAME'] : '' ),1000,randomcolor());
Please note, in order to do it similar to the way above you'd actually have to insert this into your template class.
An much better solution is to avoid using the mod that allows PHP in templates and use JavaScript in the templates to create the function, then print a call to that JavaScript function.
This will work:
CreateMyTable(FORUM_NAME,1000,red);
I also noticed that red is used without quotes - is this also a constant? If it's a variable it needs to have a $ in front of it. If it's a string it should be between quotes.
CreateMyTable(FORUM_NAME,1000,"red");
What im trying to do, is use php include within a jquery append attribute. something like this:
$('a.popup[href^=#]').click(function() {
$('body').append('<div id="content" class="popup_block"><?php include( SITE_URL . 'activity/popup.php' ) ?></div>');
My script is in a php file, server side, so that i could accomplish this, but im not sure how to go about it. When it comes to html, css etc. I can combine it and php within the php file, but when it comes to javascript, its the quotes that confuses me, and when and how to use the brackets. This might sound confusing lol. Anyways, does CDATA have anything to do with it? I've never used it before, but I should atleast learn it's use.
The PHP interpreter will only look for <?php and ?> tags and try to evaluate anything in between. It doesn't care about surrounding quotes. You need to make sure though that the result of whatever PHP does is valid Javascript.
var foo = '<?php include 'foo.php'; ?>';
becomes
var foo = 'This is the content of foo.php.';
after PHP is done with it.
If there are any quotes in foo.php, it may become this:
var foo = 'This is the 'content' of foo.php.';
which is invalid Javascript syntax. You'll need to escape any character of foo.php that may cause such invalid syntax, for example with addslashes. This can be quite cumbersome though, so I'd advise to look for an alternative this to begin with.
You can encode the value using JSON, which is definitely syntax safe:
var foo = <?php echo json_encode("Some string with 'quotes'."); ?>;
Generating code in code is always tricky, try to not do it and stick to language neutral data interchange formats like JSON or XML.
If you are 100% sure you don't have any single quotes in your include, there should be no problems with how you have it.
If you want to visualize it, copy all of your generated code from the included php file and paste it right into the main page inside of the append(). See how it looks. This will give you a good idea of what the browser will end up with.
This is the way I am currently doing it.
<?php
//show footer
echo "<script type='text/javascript'>\n";
echo "alert('Congrats');\n";
echo "</script>";
?>
Is there a better way than just to echo it?
Just put your JavaScript code outside PHP tags:
<?php
// your PHP code goes here
?>
// your javascript function out of the PHP tag.
function f() {
alert('congrats');
}
of course
?>
alert('Congrats');
<?
If you really have to execute the js by printing it from the PHP, it would at least be cleaner if you had your js functionality stored in functions in some file and then called them by printing the calls.
I recommend reserving PHP files just for PHP code and keeping your frontend code (HTML/CSS/javascript) in separate template files.
Last time I checked, mixing the presentation layer & backend code into same file was popular about 12 years ago.
Your file hierarchy for a project could look like this:
- my_project
- lib
- PHP files here
- templates
- HTML templates here
- public <- this is your document root for web server
- index.php <- just a dispatcher
- js
- images
- css
Use HEREDOCS, or break out of PHP mode into "html" mode. If the Javascript is entirely static, or has a few parts that need to have some PHP value included, drop into html mode ('?>' out of php). This will allow any decent text editor to realize that you're doing HTML and Javascript, and syntax highlight as appropriate. The following are all equivalent, but decide for yourself which is more readable:
'pure php':
<?php
echo '<script>';
echo ' var x = [' . $somePHPvar . '];';
echo ' alert(x);';
echo '<script>';
?>
'heredoc' syntax:
<?php
echo <<<EOF
<script>
var x = [{$somePHPvar}];
alert(x);
</script>
EOF;
?>
'html mode':
<?php ?>
<script>
var x = [<?php echo $somePHPVar ?>];
alert(x);
</script>
plusses/minuses for each:
pure php: you can stay in PHP mode, and your echo + $vars will be highlighted as PHP code, but the html/javascript you're echoing will be treated as plain text and colored as such (ie: all the same color)
heredoc syntax: You stay in PHP mode, but gain the benefit of not having to escape any quotes (' and ") in your code, so any html will look cleaner. Most editors will recognize PHP vars in the heredoc block and color them appropriately, but the rest of the text will be treated as text, so javascript/html look the same. Also, you cannot insert function calls into the text. You have to do those BEFORE starting the heredoc and store the results in a var, which can be inserted. The HEREDOC can also be use to assign long text blocks into a variable directly.
'html mode': The editor will see/recognize your html, javascript, AND php and color them appropriately. But this is at the cost of having to sprinkle php open/close tags anywhere you need to fill in some value dynamically. On the plus side, you can directly insert function call results (htmlspecialchars(), urlecncode(), html_strip_tags(), etc...) without having to store the values in an intermediate var. It also makes for harder-to-maintain code as your PHP is now sprinkled randomly throughough the html/javascript code.
It all boils down to what's easiest for the particular code you're working on.
You can use the model-view-controller pattern for outputting JavaScript.
You can have a "view" file where most of your JS is stored:
myJavascript.js.php:
alert('hello bob');
alert('hello <?php echo $name; ?>');
alert('whats up?');
Your controller, jsController.php:
$name = "Jane";