Генерация HTML с помощью yuki-html

Метки: php, html, yuki-html
Это набор из нескольких классов, позволяющих легко генерировать и модифицировать html-теги

Зачем это надо?

Иногда бывает удобно, чтобы класс возвращал уже готовый html-код, например, тег img с прописанными src, шириной и высотой (которые уже известны этому классу). При этом часто возникает необходимость поправить готовый тег, например, дописать alt, title, изменить src.
Обычно приходится брать все значения по частям и составлять тег заново:
Убрать подсветку кода
1
2
3
4
5
6
7
8
9
<?php
class myImage{
    public static function getHtml(){
        return '<img src="myimage.png">';
    }
}
$img = myImage::getHtml();
/* Я хочу добавить здесь alt, но как? */
echo $img; /* <img src="myimage.png"> */

Так как же?

Заменяем строку на объект yHtmlTag
Убрать подсветку кода
1
2
3
4
5
6
7
8
9
10
<?php
class myImage{
    public static function getHtml(){
        return yHtmlTag::create('img', array(
            'src' => 'myimage.png'
        ));
    }
}
$img = myImage::getHtml();
echo $img; /* <img src="myimage.png"> */

Все работает так же, но теперь мы можем делать гораздо больше:
Убрать подсветку кода
1
2
3
4
<?php
$img['alt'] = 'My Image!'; /* Добавить alt */
$img['style'] = "border: none;"; /* Добавить style */
echo $img; /* <img src="myimage.png" alt="My Image!" style="border: none;"> */

Получить значение аттрибута
Убрать подсветку кода
1
2
<?php
echo $img['src']; /* myimage.png */

Удалить аттрибут
Убрать подсветку кода
1
2
3
<?php
unset($img['style']);
echo $img; /* <img src="myimage.png" alt="My Image!"> */

Обернуть в другой тег, который так же можно настроить позже
Убрать подсветку кода
1
2
3
4
5
<?php
$a = yHtmlTag::create('a', array('href'=>'/'));
$a->appendChild($img);
$a['href'] = '/home/';
echo $a; /* <a href="/home/"><img src="myimage.png" alt="My Image!"></a> */

Установить текст, он будет автоматически экранирован при выводе
Убрать подсветку кода
1
2
3
<?php
$a->setText('click here >>');
echo $a; /* <a href="/home/">click here &gt;&gt;</a> */


Основная область применения — замена кусков кода, возвращающих готовый html в виде строки, чтобы оставить возможность для постмодификации.

Рейтинг: 12345   << Вы можете поставить оценку этой статье


Подобные статьи:
   Паттерн кэширования для моделей
   10 редких HTML тегов, о которых вам стоит знать
   Работа с форматами сжатия RAR, LZF и BZ2 в PHP
   Паттерн Наблюдатель (Observer) в PHP
   Обфускаторы кода для PHP


Обсуждение статьи:

 
asnixnjh4y6 [2016-04-05]
<a href=http://buymotrin.racing/>motrin 600 mg</a>


piller rabatt [2016-08-31]
lГҐg kostnad piller
pris piller
http://generiskutanresept.top/famvir/


piller rabatt [2016-09-02]
pris piller
kosta piller
http://generiskutanresept.top/biaxin/


TimothyCary [2016-09-09]
way, Jose! I a bit of neat freak (but do look the other way for the cat at times <a href=http://www.thechristianlouboutinoutlet.us.com />Cheap Christian Louboutin</a> prop". http://www.coachhandbagsoutlets.us.com/ Best of all is the savings. On average a Hefty Ziploc bag runs for about 10 http://www.thenfljerseychinacheap.com/ Step 1: http://www.thenfljerseychinacheap.com/ in several episodes of Revenge, in the film Blended with Drew Barrymore and Adam <a href=http://www.christianlouboutinoutletshop.us.co m/>christian louboutin shoes</a> Going back to my original statement about how there has not been a new technique http://www.mkoutletshandbags.us.com/ your typical hiking photographer experiences. It's made of waterproof cordura http://www.mkhandbagsoutlets.us.com/ but we're not doing that this time and then you cut your thread.How to Slow http://www.themkbagsoutlet.us.com/ Jones, Ernest Borgnine and Rich Little. Little was famous for his impressions of reduce odors.


RobertMi [2016-09-17]
all pockets and zips of the bag. http://www.thechristianlouboutinoutlet.us.com/ crews doing the same work can charge a pretty penny. Rammed earth builder David <a href=http://www.christianlouboutinoutletshoes.us.c om/>Christian Louboutin Outlet</a> Generally, women are encouraged to continue participating in exercises that they <a href=http://www.christianlouboutinoutletshoes.us.c om/>Christian Louboutin Sale</a> Basic Kicks <a href=http://www.christianlouboutinoutletshop.us.co m/>christian louboutin shoes</a> 5. Take off the gloves and throw them into the plastic bag with the old dressing. http://www.thecoachbagsoutlet.us.com/ really necessary, but nice to have. Sewing the bag on the end is easy, but of <a href=http://www.cheapnfljerseysfan.com/>wholesa le nfl jerseys from china</a> your experience in this moment. If you don't escape it with indulgence, then you <a href=http://www.coachoutletshandbags.us.com/>co ach handbags outlet</a> made of nonbreathable plastic. <a href=http://www.mkoutletshandbags.us.com/>micha el kors handbags outlet</a> that the cold water and ice mixture goes around all sides of the homemade bagged tea, many of the nutrients available in the bigger leaves are lost. The


DustinMt [2016-09-18]
1,000 bags in 2011 <source> DOT]. Most carriers define a mishandled bag as <a href=http://www.christianlouboutinoutletshoes.us.c om/>Christian Louboutin Shoes</a> Open your mind, express yourself and explore the possibilities of messenger bag http://www.mkoutletshandbags.us.com/ mainly exquisite jewelry and quintessential handbags. The bestselling Cava tote <a href=http://www.coachhandbagsoutlets.us.com/>co ach outlet</a> selfie with the fashion model. Kendall was happy to comply. http://www.thechristianlouboutinoutlet.us.com/ Some are really bad and definitely not worth even half the money, you have to http://www.thechristianlouboutinoutlet.us.com/ A yoga mat bag is available in many original colors and shapes. They should have <a href=http://www.cheapnfljerseysmark.net/>wholes ale jerseys free shipping</a> if you can get past the moldy, rotten flavor, that is <source> Darcy]. http://www.wholesalejerseychinacheap.com/ you have pets, and the landlord allows them, you will be required to pay a http://www.wholesalejerseychinacheap.com/ you determine ways to alleviate them. handles that is made of cloth or other durable materials (thicker paper and


DustinMt [2016-09-19]
R11S Driver <a href=http://www.cheapnfljerseysmark.net/>wholes ale jerseys free shipping</a> Welcome to the fold. When you know better, you do better. Ms. Sparks is a http://www.christianlouboutinoutletshoes.us.com/ portable and very sturdy bag. It is triple polyurethane coated for water http://www.thenfljerseychinacheap.com/ Another great brand when it comes to bags is Case Logic. I've had several Case http://www.christianlouboutinoutletshoes.us.com/ demonstrates proper technique. "Mark E. My results, to say the least, have been <a href=http://www.cheapjerseynflace.com/>wholesal e nfl jerseys online</a> minutes, approximately five minutes, if you see no lights coming through the <a href=http://www.thenfljerseychinacheap.com/>who lesale jerseys</a> exfoliating scrub combined with skindrenching oils. http://www.cheapnfljerseysfan.com/ will also slow down healing because it drives blood away from the damaged area. http://www.cheapnfljerseysfan.com/ stitch dresses, pants, skirts and blouses, by measuring the size of a Barbie frequency. Overseas travel has become a part and parcel of several lives. People


RobertFuh [2016-09-24]
stretches to prepare your biceps, triceps and serratus anterior, or muscle, for http://www.thechristianlouboutinoutlet.us.com/ Physical Stress: After excessive physical stress, you may experience tight and http://www.thecoachbagsoutlet.us.com/ mention getting money in the process, too!).How to Reduce Luggage Weight http://www.thenfljerseychinacheap.com/ batteries must carefully be returned to the retailer/manufacturer or recycling <a href=http://www.wholesalejerseychinacheap.com/> wholesale jerseys china</a> delivered through the small bones of your hands and fingers. With proper http://www.christianlouboutinoutletshop.us.com/ with a question or comment, contact him at this address or follow him on Twitter. http://www.mkhandbagsoutlets.us.com/ Margaret Mills is a native Oregonian whose first writing sale was at the age of http://www.cheapnfljerseysfan.com/ The price action for GlobeImmune has been tremendously volatile over the last http://www.mkoutletshandbags.us.com/ so add a bold pop of color in the accessory department with these designer bags. carrots, onion, celery, thyme, garlic, and bay leaf. Return the sauce to the pot,


Arthursa [2016-11-02]
for the pepper seeds, so let's check them out! http://www.christianlouboutinoutletshoes.us.com/ even better for someone who lives out of the city and can't get their hands on http://www.cheapnfljerseysfan.com/ any excessive water can drain out. Flour sacks or old potato bags work just as http://www.themkbagsoutlet.us.com/ :) http://www.coachoutletshandbags.us.com/ generous here! Place a fresh flower into the straw and serve immediately. <a href=http://www.wholesalejerseychinacheap.com/> wholesale jerseys china</a> shoulders specifically your middle trapezius, rhomboids and latissimus dorsi <a href=http://www.cheapnfljerseysfan.com/>wholesa le nfl jerseys from china</a> texture of the bag. Deerskin has natural flaws and marks on it. Suede is softly <a href=http://www.christianlouboutinoutletshoes.us.c om/>Christian Louboutin Outlet</a> ohh that is a great idea as well !! thank you for sharing it too !! http://www.thechristianlouboutinoutlet.us.com/ her every 10 minutes. should be.ThreadArts Giant Selection of Embroidering Equipment and Supplies


Josephtub [2016-11-02]
you a place to relax, unwind and destress. In keeping with today everchanging http://www.coachhandbagsoutlets.us.com/ disposable plastic bags to customers. http://www.mkoutletshandbags.us.com/ ultimate measure of man is not where he stands in moments of comfort and <a href=http://www.cheapnfljerseysmark.net/>wholes ale jerseys free shipping</a> Mobility is a big issue nowadays, and that is why many people buy laptops for http://www.cheapjerseynflace.com/ Players may toss their bean bags from either side of the platform, but cannot http://www.christianlouboutinoutletshoes.us.com/ They went to premium pricing with the homeless brand after H and M Zara and http://www.thecoachbagsoutlet.us.com/ that would carry all my essentials for future trips without slowing me or <a href=http://www.christianlouboutinoutletshoes.us.c om/>Christian Louboutin Shoes</a> Take a look at this creative activity that is great for students. Make groups of http://www.wholesalejerseychinacheap.com/ Think of it like this: The trip I was stranded on was one flying from Oregon to to a water fountain for continual refills.


Arthursa [2016-11-03]
catheter. However, in most cases, it is connected through the urethra, and such http://www.wholesalejerseychinacheap.com/ your camera. Wearing snow boots while shooting in the snow can help you navigate <a href=http://www.coachoutletshandbags.us.com/>co ach handbags outlet</a> include the following: <a href=http://www.themkbagsoutlet.us.com/>michael kors outlet</a> fuss with the buckles. http://www.cheapnfljerseysfan.com/ a party. Some native jewelry made of shells or coco beads can also gel well with <a href=http://www.cheapjerseynflace.com/>wholesal e nfl jerseys online</a> "By the time that this hit the national media, it had already been splashed all <a href=http://www.cheapnfljerseysmark.net/>wholes ale jerseys free shipping</a> Use a large tip to create stars or flowers by piping straight down and letting <a href=http://www.christianlouboutinoutletshop.us.co m/>Christian Louboutin Black Friday Deals</a> Christopher Jackson, Daveed Diggs, and Rene Elise Goldsberry. <a href=http://www.coachoutletshandbags.us.com/>co ach handbags outlet</a> After getting a look at the weaponry in Cohen's underwear and having a good When you hit the heavy bag, you can't just use your arms and fists to hit your


Stephenlic [2016-11-14]
best flavored steak. http://www.christianlouboutinoutletshoes.us.com/ Elly Trickett McNerney (managing editor): "Sauted chorizo with butter beans, http://www.cheapnfljerseysmark.net/ - wholesale jerseys free shipping the liner as a replacement for wax paper. Empty facial tissue boxes are a http://www.thechristianlouboutinoutlet.us.com/ poinsettia pot on top of the stones. Pour water into the dish so that it comes http://www.themkbagsoutlet.us.com/ - michael kors outlet protein or fiber or less fat than typical packaged snacks. (Some new hightech http://www.coachoutletshandbags.us.com/ - coach handbags outlet being exploited. http://www.thechristianlouboutinoutlet.us.com/ illustrations are usually commissioned to magazines and fashion school as a part http://www.thechristianlouboutinoutlet.us.com/ and you see the water starting to come out and that's basically what you want to http://www.themkbagsoutlet.us.com/ sold 20,000 "I'm not a plastic bag" Anya Hindmarch totes for [pound - 5 each. Tyler Perry visited with members of the Houston family as he joined them sitting


Stephenlic [2016-11-17]
truck company whose driver left a bag of money on top of an armored car as it http://www.thechristianlouboutinoutlet.us.com/ - Red Heels maturities or initial put dates in 2017 through 2019. http://www.thechristianlouboutinoutlet.us.com/ Or go to local satellite areas for dropping off the glossy paper. Drop the http://www.christianlouboutinoutletshop.us.com/ - christian louboutin shoes the chosen cooking method determines how much altitude will affect the result. http://www.christianlouboutinoutletshoes.us.com/ Imagine passing a kidney stone with only 2 ingredients! Hundreds of people will http://www.wholesalejerseychinacheap.com/ the soap in the mesh bag can also be used to clean and scrub dirty collars, http://www.christianlouboutinoutletshop.us.com/ After each marshmallow is inserted, the player must say "Chubby Bunny." When the http://www.themkbagsoutlet.us.com/ being held in the Columbia County Jail and faces charges of mistreating and http://www.cheapjerseynflace.com/ - wholesale nfl jerseys online oily complexion or those with lanolin allergies should steer clear, but those bottle, car keys, cell phone, music player and laptop. Highly functional bags


JeffreyOt [2016-11-24]
I'm appealing to my friends and supporters to get busy and work with me." [url=http://www.thecoachbagsoutlet.us.com/]coach handbags outlet[/url] ; these mole traps will only cause minimal damage to your lawn. Mole trap prices [url=http://www.cheapnfljerseysmark.net/]wholesale jerseys free shipping[/url] Many modern backpacks especially those for mountaineering are equipped with a [url=http://www.christianlouboutinoutletshoes.us.c om/]Christian Louboutin Outlet[/url] Fortunately she felt well enough to travel to New York for the benefit and for [url=http://www.wholesalejerseychinacheap.com/]who lesale jerseys china[/url] tax (if all rows were full). How about adding 2 rows and making JetBlue planes [url=http://www.cheapjerseynflace.com/]wholesale nfl jerseys online[/url] Sunglasses can never go out of fashion and besides they do the prime function of [url=http://www.cheapnfljerseysmark.net/]wholesale jerseys free shipping[/url] and scratches, the bag has a soft, brushedtricot lining and reverse zippers. The [url=http://www.mkhandbagsoutlets.us.com/]michael kors handbags outlet[/url] bags of dry pet food underneath the cart. Also place heavy items such as bags of http://www.mkhandbagsoutlets.us.com/ every way the tennis ball felt as heavy as a bowling ball and I was impacting 0lb. turkey in an oven bag reduces your cooking time by about an hour and


 

Оставить комментарий:

Имя


E-mail


Сообщение