Как получить заголовок элемента из базы данных и отправить его в шаблон заголовка в CodeIgniter
Я пишу приложение в CodeIgniter, где я указываю метатег <title>
на каждой странице каждого контроллера, который мне удалось отправить в шаблон заголовка. Однако теперь я создал приложение, которое извлекает кредитные карты и их заголовки из базы данных через модель CodeIgniter. Я хотел бы автоматически выбрать и использовать имя кредитной карты в <title>
, чтобы мне не нужно было ее вручную менять, но я немного зациклен на том, как действовать.
Это мой код на данный момент:
контроллер
public function show($card = NULL)
{
$data['query'] = $this->Listing_model->get_card($card);
$header["page_title"] = from the model
$this->load->view('includes/header',$header);
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
Model
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 0,1);
return $query->result();
}
Я занимаюсь официальной документацией CodeIgniter при создании этого приложения, но до сих пор не повезло. Любые решения?
Ответы
Ответ 1
Попробуйте это
- Изменена модель.
- Изменен контроллер.
В модели
function get_card($card)
{
$query = $this->db->query("SELECT * FROM table_name WHERE creditcards = '$card' ");
$result = $query->result_array();
$count = count($result); # New
if(empty($count)){ # New
return FALSE;
}
elseif($count > 1){ # New
return 0;
}
else{
return $result;
}
}
В контроллере
public function show($card)
{
$result = $this->Listing_model->get_card($card); # Changed
if($result == FALSE){ # New
echo "No Data Found";
}
elseif($result == 0){ # New
echo "Multiple Data Found";
}
else{
$data["page_title"] = $result[0]['field_name']; # Changed
$this->load->view('includes/header',$data); # Changed
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
}
В представлении
<?php echo (!empty($page_title)) ? $page_title : ''; ?> # Changed
Ответ 2
Создайте базовый контроллер. По умолчанию это значение application/core/MY_Controller.php =>
, которое можно изменить через конфигурацию.
Используя $this->site_data
, вы можете добавлять переменные в свой базовый класс и использовать их в каждом представлении/представлении
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('your model');
$result = $this->Listing_model->get_card($card);
$this->site_data['query']=$result;
$this->site_data_header["page_title"] = $result['get the property you want'];//this is possible, as get_card returns 1 result
}
}
class YourClass extends MY_Controller
{
function __construct()
{
parent::__construct();
}
public function show($card = NULL)
{
//you don't need to split the variables
//for header and the rest
$this->load->view('includes/header',$this->site_data_header);
$this->load->view('listings/listing_card',$this->site_data);
$this->load->view('includes/footer');
}
}
И я думаю, что ваш get_where не прав:
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
ваш предел равен 0
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 1,0);//limit 1 offset 0
return $query->result();
}
доступ к данным в вашем представлении
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
Ответ 3
Простой пример:
контроллер
$query = $this->Listing_model->get_card($card);
$query = $query->row();
$header["page_title"] = $query->title;
Вид
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
Ответ 4
Вы можете создать базовый контроллер и распространить все остальные контроллеры на этот базовый контроллер.
Подобно этому
<?php
class MY_Controller extends CI_Controller {
public $data = array();
function __construct() {
parent::__construct();
$this->data['errors'] = array();
$this->data['site_name'] = config_item('site_name');
}
}
Затем в вашем контроллере
class Test extends MY_Controller
{
function __construct() {
parent::__construct();
$this->data['meta_title'] = 'Your Title';
}
}
И у вас есть доступ к названию страницы, как это:
echo("<title>.$site_name.</title>");
Ответ 5
Вам может потребоваться создать несколько маршрутов для вашей функции show. Маршрутизация URI Codeigniter
$route['your_controller_name/show/(:any)'] = 'your_controller_name/show/$1';
Я не уверен, что вы настроили htaccess для своего основного каталога, чтобы удалить index.php
с вашего URL.
Попробуйте этот код ниже
Модель:
<?php
class Listing_model extends CI_Model {
function get_card_title($card) {
$this->db->where('slug', $card);
$query = $this->db->get($this->db->dbprefix . 'creditcards');
if ($query->num_rows() > 0) {
$row = $quer->row();
return $row->title;
} else {
return false;
}
}
}
Контроллер: Your_controller_name.php
<?php
class Your_controller_name extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('listing_model');
}
public function show($card) {
$data['title'] = $this->listing_model->get_card_title($card);
$this->load->view('includes/header', $data);
$this->load->view('listings/listing_card', $data);
$this->load->view('includes/footer');
}
}
Вид:
<head>
<title><?php echo $title;?></title>
</head>
Ответ 6
контроллер
$card_data= $this->Listing_model->get_card($card); //Your model returns an array of objects
$header["page_title"] = $card_data[0]->title; //grab value of 'title' property of first object returned from model.
$this->load->view('includes/header',$header);
Просмотр
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
Ответ 7
Попробуйте следующее:
function get_card($card = FALSE)
{
$data = $this->db->get_where('creditcards', array('slug' => $card), 0,1)->result();
$data->title = $data[0]->title;
return $data;
}
Ответ 8
контроллер
$query = $this->Listing_model->get_card($card);
var_dump($query);
//Your $query may be some data got from db;
$card_name = "";
if(!empty($query)){
$card_name = $query[0]->name; //You must verify the name attribute and it should in the $query result;
}
$header["page_title"] = $card_name;
Вид
<title><?php echo (!isset($page_title) ? '' : $page_title) ?></title>
Ответ 9
В своем карточном представлении введите:
foreach ($query as $rec){
<title><?php echo $rec->title ?></title>
}
замените "title" на имя столбца в вашей базе данных, в котором хранится название кредитной карты... поэтому вы передаете результаты запроса, который вы запускали в своем контроллере, к этому представлению, а затем используя foreach цикл для отображения данных конкретной кредитной карты
Ответ 10
Вы можете использовать библиотеку шаблонов для обеспечения надежности и использовать следующим образом:
контроллер
$this->template->title('Home :: ' . $this->data['metadata']['site_name'])
->set_layout('home_layout')
->build('listing_card', $this->data);
Просмотры
<title><?php echo $template['title']; ?></title>
<?php echo $template['metadata']; ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Ссылка: https://github.com/philsturgeon/codeigniter-template
Ответ 11
Контроллер:
$data["page_title"] = $result[0]['title_field'];
Вид:
и вам просто нужно записать в свой заголовочный файл, например:
<title><?php echo $page_title; ?></title>
Ответ 12
В вашей модели - не возвращайте $query->result()
, просто верните $query
:
function get_card($card = FALSE)
{
$query = $this->db->get_where('creditcards', array('slug' => $card), 0,1);
return $query;
}
Контроллер:
public function show($card = NULL)
{
// verify that you got something back from the database
// or show an error
if( ! $query = $this->Listing_model->get_card($card) )
{
$this->_showNoResultsFor($card) ;
}
else
{
// get one record from the query using row()
$onecard = $query->row() ;
// assign the title using whatever your field name is called
$header["page_title"] = $onecard->thetitle ;
// Now assign the query result() to data
$data['query'] = $query->result() ;
$this->load->view('includes/header',$header);
$this->load->view('listings/listing_card',$data);
$this->load->view('includes/footer');
}
}
Ответ 13
Просто чтобы добавить еще один, нет причин, по которым это не должно работать:
$data['query'] = $this->Listing_model->get_card($card);
$this->load->view('header', array('page_title' => $data['query'][0]->column_name));
//Will there only be one result? Consider returning $query->row(). Multiple,
//loop through and set one title
На ваш взгляд:
<title><?=isset($page_title) ? $page_title : "";?></title>
Если это не работает, ваш запрос не возвращает то, что вы думаете.