Страница 1 из 1
"Shorcode" yii2
Добавлено: 2019.11.05, 16:06
dps_guest
Например есть категория авто
и есть разные марки
- бмв
-мерседес и т.д.
СЕО описание записывает только один раз для категории авто.
А для марок получается что дубли.
Категории и марки связаны много к одному, получается категории могут быть и другие не только Авто а и мото как пример.
По этому хочеться какой-то шорткод чтобы можно как и просто марку подставлять по умолчанию так же и id может страницы и для неё другой текст совсем.
Подскажите как реализовать данное может уже похожее есть, буду благодарный.
Re: "Shorcode" yii2
Добавлено: 2019.11.05, 17:06
unknownby
Для категорий и марок в БД делаешь поля с СЕО описанием.
Когда выводишь страницу с категорией, выдаешь значение из поля БД категорий, если выдается страница марок, то берется из БД марок.
Оптимально по-моему.
Re: "Shorcode" yii2
Добавлено: 2019.11.18, 15:55
dps_guest
А как добавить переменную в админке?
Вся суть в том что информация для каждого товара может быть разная.
Re: "Shorcode" yii2
Добавлено: 2019.11.18, 16:04
dps_guest
Пример :
Текст текст текст текст текст текст [brand=1 text="TEST 5"] текст текст текст текст .
И в нужном месте если ето бренд=1 вставиться TEST 5.
Re: "Shorcode" yii2
Добавлено: 2019.11.18, 17:41
yiiliveext
Рендерите в переменную, находите регуляркой шорткод, парсите и заменяете.
Возвращаете результат.
Re: "Shorcode" yii2
Добавлено: 2019.11.28, 22:56
dps_guest
А можно какой-то примитивный пример?
может есть готовая библиотека /addons ?
Re: "Shorcode" yii2
Добавлено: 2019.11.29, 09:18
unknownby
Если суть задачи как я сейчас понял, а именно: есть текст на странице, одинаковый для всех, но чтобы вставлялось в текст значение переменной, для какого товара открыта данная страница.
Модель подгружается же для страницы?
Код: Выделить всё
return $this->render('product', [
'model' => $model,
]);
То можно использовать модель.
Код: Выделить всё
Текст текст текст <?= $model->brand_name ?> текст текст текст.
Может можно увидеть модель, вьюху и контроллер? Чтоб понимать где и что выводить собираешься.
Re: "Shorcode" yii2
Добавлено: 2019.11.29, 10:47
someweb
Пример:
https://gist.github.com/dukeofharen/e2c ... 408b53d743
Перед тем как передать во view прогоняете текст через него.
Re: "Shorcode" yii2
Добавлено: 2019.12.03, 16:45
dps_guest
Понял, супер.
Спасибо.
Re: "Shorcode" yii2
Добавлено: 2019.12.04, 16:47
dps_guest
А подскажите как взять текст из [cat id='1']текстекст текст текст[/cat]
а то получаеться в $data только идишник
Код: Выделить всё
"cat" => function($data){
$content_desc = "";
if(isset($data["id"])){
$content_desc = print_r($data);
}
return $content_desc;
}
);
function handleShortcodes($content_desc, $shortcodes){
foreach($shortcodes as $key => $function){
$dat = array();
preg_match_all("/\[".$key." (.+?)\](.*?)\[\/".$key."\]/s", $content_desc, $dat);
if(count($dat) > 0 && $dat[0] != array() && isset($dat[1])){
$i = 0;
$actual_string = $dat[0];
foreach($dat[1] as $temp){
$temp = explode(" ", $temp);
$params = array();
foreach ($temp as $d){
list($opt, $val) = explode("=", $d);
$params[$opt] = trim($val, '"');
}
$content_desc = str_replace($actual_string[$i], $function($params), $content_desc);
$i++;
}
}
}
return $content_desc;
}
Re: "Shorcode" yii2
Добавлено: 2019.12.04, 18:02
yiiliveext
Код: Выделить всё
<?php
//The content which should be parsed
$content = '<p>Hello, my name is John an my age is [calc-age day="4" month="10" year="1991"]years[/calc-age].</p>';
$content .= '<p>Hello, my name is Carol an my age is [calc-age day="26" month="11" year="1996"].</p>';
//The array with all the shortcode handlers. This is just a regular associative array with anonymous functions as values. A very cool new feature in PHP, just like callbacks in JavaScript or delegates in C#.
$shortcodes = array(
"calc-age" => function($data){
$content = "";
//Calculate the age
if(isset($data["day"], $data["month"], $data["year"])){
$age = date("Y") - $data["year"];
if(date("m") < $data["month"]){
$age--;
}
if(date("m") == $data["month"] && date("d") < $data["day"]){
$age--;
}
$content = $age;
}
return $content . (empty($data['text']) ? '' : ' ' . $data['text']);
}
);
//http://stackoverflow.com/questions/18196159/regex-extract-variables-from-shortcode
function handleShortcodes($content, $shortcodes){
//Loop through all shortcodes
foreach($shortcodes as $key => $function){
$dat = array();
preg_match_all("#\[".$key." (.+?)\]((.*?)\[/".$key."\])?#", $content, $dat);
if(count($dat) > 0 && $dat[0] != array() && isset($dat[1]) && isset($dat[3])){
$i = 0;
$actual_string = $dat[0];
foreach($dat[1] as $temp){
$temp = explode(" ", $temp);
$params = array();
foreach ($temp as $d){
list($opt, $val) = explode("=", $d);
$params[$opt] = trim($val, '"');
}
$params['text'] = $dat[3][$i];
$content = str_replace($actual_string[$i], $function($params), $content);
$i++;
}
}
}
return $content;
}
echo handleShortcodes($content, $shortcodes);
?>
Re: "Shorcode" yii2
Добавлено: 2019.12.19, 17:05
dps_guest
Что-то не могу разобраться теперь , а как вывести если просто бренд по шоткоду.
Код: Выделить всё
$shortcodes = array(...
"brand"=>function($data) {
$content_desc = "";
$content_desc = $content_desc. (empty($data['brand']) ? '' : ' ' . $data['brand']);
return $content_desc;
},...
);
а в функции
Код: Выделить всё
function handleShortcodes($content_desc, $shortcodes,$id){
foreach($shortcodes as $key => $function){
$dat = array();
preg_match_all("#\[".$key." (.+?)\]((.*?)\[/".$key."\])?#", $content_desc, $dat);
if(count($dat) > 0 && $dat[0] != array() && isset($dat[1]) && isset($dat[3])){
$i = 0;
$actual_string = $dat[0];
foreach($dat[1] as $temp){
$temp = explode(" ", $temp);
$params = array();
foreach ($temp as $d){
list($opt, $val) = explode("=", $d);
$params[$opt] = trim($val, '"');
}
$params['text'] = $dat[3][$i];
$params['id_original']=$id;
$content_desc = str_replace($actual_string[$i], $function($params), $content_desc);
$i++;
}
}
else if($key=="brand"){
$actual_string = $dat[0];
array_push($dat,'BRREEEND');
$content_desc = str_replace($actual_string,$dat[4],$content_desc);
}
}
return $content_desc;
}
Выводит мне посто шорткод [brand] и все...
Хотя должно вывести BRREEEND
Re: "Shorcode" yii2
Добавлено: 2019.12.19, 17:39
yiiliveext
html приведите и что вы хотите получить
И зачем вы вообще лезете в функцию разбора шорткодов? Обработка производится в анонимных функциях массива $shortcodes
Код: Выделить всё
$shortcodes = array(
"brand"=>function($data) {
return 'BREEND';
}
);
$content = '<p>My brand is - [brand].</p>';
echo handleShortcodes($content, $shortcodes); //не изменяйте эту функцию, все что надо я уже там написал.
Выведет <p>My brand is - BREEND.</p>
Re: "Shorcode" yii2
Добавлено: 2019.12.19, 18:09
dps_guest
вывело
23 asdasdasdadsasd asd asdasdasd asdt t444 [brand] 23
хотя с возрастом шорт сработал.
не помогло.
Re: "Shorcode" yii2
Добавлено: 2019.12.19, 18:24
yiiliveext
Вы читать умеете? Когда научитесь, сразу все заработает.
Для особо одаренных
http://sandbox.onlinephpfunctions.com/c ... c5314fe069
Re: "Shorcode" yii2
Добавлено: 2019.12.20, 12:29
dps_guest
разобрался в чем проблема была,)
спасибо.