Я плохо знаком с PHP, и я не могу выяснить то, что правила для использования функции эха. Например, если я должен повторить большой блок css/js, я должен добавить эхо к каждой строке текста или есть ли способ повторить большой блок кода с единственным эхом?
Когда я пытаюсь повторить большой блок кода как этот, я получаю ошибку:
if (is_single()) {
echo '<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: myname@example.com');
});
</script>';
}else {
}
Существует ли лучший способ повторить большие блоки кода без большой работы (добавляющий эхо к каждой строке, например)?
Один из вариантов - выйти из блока php и просто написать HTML.
Завершите PHP кодом после открывающей фигурной скобки оператора if:
if (is_single()) { ?>
Затем удалите echo '
и ';
После всего вашего html и css, перед закрытием }
, напишите:
<? } else {
Если текст, который вы хотите написать на странице, является динамическим, это становится немного сложнее, но пока это должно работать нормально.
Синтаксис Heredoc может быть очень полезным:
// start the string with 3 <'s and then a word
// it doesn't have to be any particular string or length
// but it's common to make it in all caps.
echo <<< EOT
in here is your string
it has the same variable substitution rules
as a double quoted string.
when you end it, put the indicator word at the
start of the line (no spaces before it)
and put a semicolon after it
EOT;
Отображение текста, содержащего разрывы строк, допустимо, и нет ограничений на количество текста или строк, которые вы можете отображать. сразу (за исключением доступной памяти).
Ошибка в вашем коде вызвана неэкранированными одинарными кавычками, которые появляются в строке.
См. Эту строку:
$('input_6').hint('ex: myname@example.com');
Вам нужно будет избегать одинарных кавычек в строке PHP, независимо от того, одинарная она или нет.
Однако есть еще один хороший способ отобразить большие строки - закрыть блок PHP и открыть его позже:
if (is_single()) {
?>
<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: myname@example.com');
});
</script>
<?php
}else {
}
Или другой вариант, который, вероятно, лучше для читабельности, состоит в том, чтобы поместить весь этот статический HTML в другую страницу и включите () ее.
Посмотрите heredoc . Пример:
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
echo <<<"FOOBAR"
Hello World!
FOOBAR;
Это также nowdoc , но анализ внутри блока не выполняется.
echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
Чувак, PHP - это не Perl!
PHP можно просто избежать из HTML :)
http://www.php.net/manual/en/language.basic-syntax.phpmode.php
if (is_single()) {
//now we just close PHP tag
?>
</style>
<script>
<blah blah blah>
<?php
//open it back. here is your PHP again. easy!
}
?>
Интересно, почему так много людей придерживаются уродливого heredoc.
Ваша проблема на самом деле вызвана:
$('input_6').hint('ex: myname@example.com');
Вам нужно избегать одинарных кавычек, чтобы быть \ '
Однако: Использование Heredoc - гораздо лучшая идея, так как это будет намного чище общий.