/usr/share/pyshared/zope.viewlet-3.7.2.egg-info/PKG-INFO is in python-zope.viewlet 3.7.2-0ubuntu4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 | Metadata-Version: 1.1
Name: zope.viewlet
Version: 3.7.2
Summary: Zope Viewlets
Home-page: http://pypi.python.org/pypi/zope.viewlet
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: Viewlets provide a generic framework for building pluggable user interfaces.
Detailed Documentation
**********************
=============================
Viewlets and Viewlet Managers
=============================
Let's start with some motivation. Using content providers allows us to insert
one piece of HTML content. In most Web development, however, you are often
interested in defining some sort of region and then allow developers to
register content for those regions.
>>> from zope.viewlet import interfaces
Design Notes
------------
As mentioned above, besides inserting snippets of HTML at places, we more
frequently want to define a region in our page and allow specialized content
providers to be inserted based on configuration. Those specialized content
providers are known as viewlets and are only available inside viewlet
managers, which are just a more complex example of content providers.
Unfortunately, the Java world does not implement this layer separately. The
viewlet manager is most similar to a Java "channel", but we decided against
using this name, since it is very generic and not very meaningful. The viewlet
has no Java counterpart, since Java does not implement content providers using
a component architecture and thus does not register content providers
specifically for viewlet managers, which I believe makes the Java
implementation less useful as a generic concept. In fact, the main design
goal in the Java world is the implementation of reusable and sharable
portlets. The scope for Zope 3 is larger, since we want to provide a generic
framework for building pluggable user interfaces.
The Viewlet Manager
-------------------
In this implementation of viewlets, those regions are just content providers
called viewlet managers that manage a special type of content providers known
as viewlets. Every viewlet manager handles the viewlets registered for it:
>>> class ILeftColumn(interfaces.IViewletManager):
... """Viewlet manager located in the left column."""
You can then create a viewlet manager using this interface now:
>>> from zope.viewlet import manager
>>> LeftColumn = manager.ViewletManager('left', ILeftColumn)
Now we have to instantiate it:
>>> import zope.interface
>>> class Content(object):
... zope.interface.implements(zope.interface.Interface)
>>> content = Content()
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> class View(object):
... zope.interface.implements(IBrowserView)
... def __init__(self, context, request):
... pass
>>> view = View(content, request)
>>> leftColumn = LeftColumn(content, request, view)
So initially nothing gets rendered:
>>> leftColumn.update()
>>> leftColumn.render()
u''
But now we register some viewlets for the manager
>>> import zope.component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> class WeatherBox(object):
... zope.interface.implements(interfaces.IViewlet)
...
... def __init__(self, context, request, view, manager):
... self.__parent__ = view
...
... def update(self):
... pass
...
... def render(self):
... return u'<div class="box">It is sunny today!</div>'
>>> # Create a security checker for viewlets.
>>> from zope.security.checker import NamesChecker, defineChecker
>>> viewletChecker = NamesChecker(('update', 'render'))
>>> defineChecker(WeatherBox, viewletChecker)
>>> zope.component.provideAdapter(
... WeatherBox,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, ILeftColumn),
... interfaces.IViewlet, name='weather')
>>> from zope.location.interfaces import ILocation
>>> class SportBox(object):
... zope.interface.implements(interfaces.IViewlet,
... ILocation)
...
... def __init__(self, context, request, view, manager):
... self.__parent__ = view
...
... def update(self):
... pass
...
... def render(self):
... return u'<div class="box">Patriots (23) : Steelers (7)</div>'
>>> defineChecker(SportBox, viewletChecker)
>>> zope.component.provideAdapter(
... SportBox,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, ILeftColumn),
... interfaces.IViewlet, name='sport')
and thus the left column is filled. Note that also events get fired
before viewlets are updated. We register a simple handler to
demonstrate this behaviour.
>>> from zope.contentprovider.interfaces import IBeforeUpdateEvent
>>> events = []
>>> def handler(ev):
... events.append(ev)
>>> zope.component.provideHandler(handler, (IBeforeUpdateEvent,))
>>> leftColumn.update()
>>> [(ev, ev.object.__class__.__name__) for ev in events]
[(<zope.contentprovider.interfaces.BeforeUpdateEvent...>, 'SportBox'),
(<zope.contentprovider.interfaces.BeforeUpdateEvent...>, 'WeatherBox')]
>>> print leftColumn.render()
<div class="box">Patriots (23) : Steelers (7)</div>
<div class="box">It is sunny today!</div>
But this is of course pretty lame, since there is no way of specifying how the
viewlets are put together. But we have a solution. The second argument of the
``ViewletManager()`` function is a template in which we can specify how the
viewlets are put together:
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> leftColTemplate = os.path.join(temp_dir, 'leftCol.pt')
>>> open(leftColTemplate, 'w').write('''
... <div class="left-column">
... <tal:block repeat="viewlet options/viewlets"
... replace="structure viewlet/render" />
... </div>
... ''')
>>> LeftColumn = manager.ViewletManager('left', ILeftColumn,
... template=leftColTemplate)
>>> leftColumn = LeftColumn(content, request, view)
TODO: Fix this silly thing; viewlets should be directly available.
As you can see, the viewlet manager provides a global ``options/viewlets``
variable that is an iterable of all the available viewlets in the correct
order:
>>> leftColumn.update()
>>> print leftColumn.render().strip()
<div class="left-column">
<div class="box">Patriots (23) : Steelers (7)</div>
<div class="box">It is sunny today!</div>
</div>
If a viewlet provides ILocation the ``__name__`` attribute of the
viewlet is set to the name under which the viewlet is registered.
>>> [getattr(viewlet, '__name__', None) for viewlet in leftColumn.viewlets]
[u'sport', None]
You can also lookup the viewlets directly for management purposes:
>>> leftColumn['weather']
<WeatherBox ...>
>>> leftColumn.get('weather')
<WeatherBox ...>
The viewlet manager also provides the __contains__ method defined in
IReadMapping:
>>> 'weather' in leftColumn
True
>>> 'unknown' in leftColumn
False
If the viewlet is not found, then the expected behavior is provided:
>>> leftColumn['stock']
Traceback (most recent call last):
...
ComponentLookupError: No provider with name `stock` found.
>>> leftColumn.get('stock') is None
True
Customizing the default Viewlet Manager
---------------------------------------
One important feature of any viewlet manager is to be able to filter and sort
the viewlets it is displaying. The default viewlet manager that we have been
using in the tests above, supports filtering by access availability and
sorting via the viewlet's ``__cmp__()`` method (default). You can easily
override this default policy by providing a base viewlet manager class.
In our case we will manage the viewlets using a global list:
>>> shown = ['weather', 'sport']
The viewlet manager base class now uses this list:
>>> class ListViewletManager(object):
...
... def filter(self, viewlets):
... viewlets = super(ListViewletManager, self).filter(viewlets)
... return [(name, viewlet)
... for name, viewlet in viewlets
... if name in shown]
...
... def sort(self, viewlets):
... viewlets = dict(viewlets)
... return [(name, viewlets[name]) for name in shown]
Let's now create a new viewlet manager:
>>> LeftColumn = manager.ViewletManager(
... 'left', ILeftColumn, bases=(ListViewletManager,),
... template=leftColTemplate)
>>> leftColumn = LeftColumn(content, request, view)
So we get the weather box first and the sport box second:
>>> leftColumn.update()
>>> print leftColumn.render().strip()
<div class="left-column">
<div class="box">It is sunny today!</div>
<div class="box">Patriots (23) : Steelers (7)</div>
</div>
Now let's change the order...
>>> shown.reverse()
and the order should switch as well:
>>> leftColumn.update()
>>> print leftColumn.render().strip()
<div class="left-column">
<div class="box">Patriots (23) : Steelers (7)</div>
<div class="box">It is sunny today!</div>
</div>
Of course, we also can remove a shown viewlet:
>>> weather = shown.pop()
>>> leftColumn.update()
>>> print leftColumn.render().strip()
<div class="left-column">
<div class="box">Patriots (23) : Steelers (7)</div>
</div>
WeightOrderedViewletManager
---------------------------
The weight ordered viewlet manager offers ordering viewlets by a additional
weight argument. Viewlets which doesn't provide a weight attribute will get
a weight of 0 (zero).
Let's define a new column:
>>> class IWeightedColumn(interfaces.IViewletManager):
... """Column with weighted viewlet manager."""
First register a template for the weight ordered viewlet manager:
>>> weightedColTemplate = os.path.join(temp_dir, 'weightedColTemplate.pt')
>>> open(weightedColTemplate, 'w').write('''
... <div class="weighted-column">
... <tal:block repeat="viewlet options/viewlets"
... replace="structure viewlet/render" />
... </div>
... ''')
And create a new weight ordered viewlet manager:
>>> from zope.viewlet.manager import WeightOrderedViewletManager
>>> WeightedColumn = manager.ViewletManager(
... 'left', IWeightedColumn, bases=(WeightOrderedViewletManager,),
... template=weightedColTemplate)
>>> weightedColumn = WeightedColumn(content, request, view)
Let's create some viewlets:
>>> from zope.viewlet import viewlet
>>> class FirstViewlet(viewlet.ViewletBase):
...
... weight = 1
...
... def render(self):
... return u'<div>first</div>'
>>> class SecondViewlet(viewlet.ViewletBase):
...
... weight = 2
...
... def render(self):
... return u'<div>second</div>'
>>> class ThirdViewlet(viewlet.ViewletBase):
...
... weight = 3
...
... def render(self):
... return u'<div>third</div>'
>>> class UnWeightedViewlet(viewlet.ViewletBase):
...
... def render(self):
... return u'<div>unweighted</div>'
>>> defineChecker(FirstViewlet, viewletChecker)
>>> defineChecker(SecondViewlet, viewletChecker)
>>> defineChecker(ThirdViewlet, viewletChecker)
>>> defineChecker(UnWeightedViewlet, viewletChecker)
>>> zope.component.provideAdapter(
... ThirdViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IWeightedColumn),
... interfaces.IViewlet, name='third')
>>> zope.component.provideAdapter(
... FirstViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IWeightedColumn),
... interfaces.IViewlet, name='first')
>>> zope.component.provideAdapter(
... SecondViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IWeightedColumn),
... interfaces.IViewlet, name='second')
>>> zope.component.provideAdapter(
... UnWeightedViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IWeightedColumn),
... interfaces.IViewlet, name='unweighted')
And check the order:
>>> weightedColumn.update()
>>> print weightedColumn.render().strip()
<div class="weighted-column">
<div>unweighted</div>
<div>first</div>
<div>second</div>
<div>third</div>
</div>
ConditionalViewletManager
-------------------------
The conditional ordered viewlet manager offers ordering viewlets by a
additional weight argument and filters by the available attribute if a
supported by the viewlet. Viewlets which doesn't provide a available attribute
will not get skipped. The default weight value for viewlets which doesn't
provide a weight attribute is 0 (zero).
Let's define a new column:
>>> class IConditionalColumn(interfaces.IViewletManager):
... """Column with weighted viewlet manager."""
First register a template for the weight ordered viewlet manager:
>>> conditionalColTemplate = os.path.join(temp_dir,
... 'conditionalColTemplate.pt')
>>> open(conditionalColTemplate, 'w').write('''
... <div class="conditional-column">
... <tal:block repeat="viewlet options/viewlets"
... replace="structure viewlet/render" />
... </div>
... ''')
And create a new conditional viewlet manager:
>>> from zope.viewlet.manager import ConditionalViewletManager
>>> ConditionalColumn = manager.ViewletManager(
... 'left', IConditionalColumn, bases=(ConditionalViewletManager,),
... template=conditionalColTemplate)
>>> conditionalColumn = ConditionalColumn(content, request, view)
Let's create some viewlets. We also use the previous viewlets supporting no
weight and or no available attribute:
>>> from zope.viewlet import viewlet
>>> class AvailableViewlet(viewlet.ViewletBase):
...
... weight = 4
...
... available = True
...
... def render(self):
... return u'<div>available</div>'
>>> class UnAvailableViewlet(viewlet.ViewletBase):
...
... weight = 5
...
... available = False
...
... def render(self):
... return u'<div>not available</div>'
>>> defineChecker(AvailableViewlet, viewletChecker)
>>> defineChecker(UnAvailableViewlet, viewletChecker)
>>> zope.component.provideAdapter(
... ThirdViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IConditionalColumn),
... interfaces.IViewlet, name='third')
>>> zope.component.provideAdapter(
... FirstViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IConditionalColumn),
... interfaces.IViewlet, name='first')
>>> zope.component.provideAdapter(
... SecondViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IConditionalColumn),
... interfaces.IViewlet, name='second')
>>> zope.component.provideAdapter(
... UnWeightedViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IConditionalColumn),
... interfaces.IViewlet, name='unweighted')
>>> zope.component.provideAdapter(
... AvailableViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IConditionalColumn),
... interfaces.IViewlet, name='available')
>>> zope.component.provideAdapter(
... UnAvailableViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IConditionalColumn),
... interfaces.IViewlet, name='unavailable')
And check the order:
>>> conditionalColumn.update()
>>> print conditionalColumn.render().strip()
<div class="conditional-column">
<div>unweighted</div>
<div>first</div>
<div>second</div>
<div>third</div>
<div>available</div>
</div>
Viewlet Base Classes
--------------------
To make the creation of viewlets simpler, a set of useful base classes and
helper functions are provided.
The first class is a base class that simply defines the constructor:
>>> base = viewlet.ViewletBase('context', 'request', 'view', 'manager')
>>> base.context
'context'
>>> base.request
'request'
>>> base.__parent__
'view'
>>> base.manager
'manager'
But a default ``render()`` method implementation is not provided:
>>> base.render()
Traceback (most recent call last):
...
NotImplementedError: `render` method must be implemented by subclass.
If you have already an existing class that produces the HTML content in some
method, then the ``SimpleAttributeViewlet`` might be for you, since it can be
used to convert any class quickly into a viewlet:
>>> class FooViewlet(viewlet.SimpleAttributeViewlet):
... __page_attribute__ = 'foo'
...
... def foo(self):
... return 'output'
The `__page_attribute__` attribute provides the name of the function to call for
rendering.
>>> foo = FooViewlet('context', 'request', 'view', 'manager')
>>> foo.foo()
'output'
>>> foo.render()
'output'
If you specify `render` as the attribute an error is raised to prevent
infinite recursion:
>>> foo.__page_attribute__ = 'render'
>>> foo.render()
Traceback (most recent call last):
...
AttributeError: render
The same is true if the specified attribute does not exist:
>>> foo.__page_attribute__ = 'bar'
>>> foo.render()
Traceback (most recent call last):
...
AttributeError: 'FooViewlet' object has no attribute 'bar'
To create simple template-based viewlets you can use the
``SimpleViewletClass()`` function. This function is very similar to its view
equivalent and is used by the ZCML directives to create viewlets. The result
of this function call will be a fully functional viewlet class. Let's start by
simply specifying a template only:
>>> template = os.path.join(temp_dir, 'demoTemplate.pt')
>>> open(template, 'w').write('''<div>contents</div>''')
>>> Demo = viewlet.SimpleViewletClass(template)
>>> print Demo(content, request, view, manager).render()
<div>contents</div>
Now let's additionally specify a class that can provide additional features:
>>> class MyViewlet(object):
... myAttribute = 8
>>> Demo = viewlet.SimpleViewletClass(template, bases=(MyViewlet,))
>>> MyViewlet in Demo.__bases__
True
>>> Demo(content, request, view, manager).myAttribute
8
The final important feature is the ability to pass in further attributes to
the class:
>>> Demo = viewlet.SimpleViewletClass(
... template, attributes={'here': 'now', 'lucky': 3})
>>> demo = Demo(content, request, view, manager)
>>> demo.here
'now'
>>> demo.lucky
3
As for all views, they must provide a name that can also be passed to the
function:
>>> Demo = viewlet.SimpleViewletClass(template, name='demoViewlet')
>>> demo = Demo(content, request, view, manager)
>>> demo.__name__
'demoViewlet'
In addition to the the generic viewlet code above, the package comes with two
viewlet base classes and helper functions for inserting CSS and Javascript
links into HTML headers, since those two are so very common. I am only going
to demonstrate the helper functions here, since those demonstrations will
fully demonstrate the functionality of the base classes as well.
The viewlet will look up the resource it was given and tries to produce the
absolute URL for it:
>>> class JSResource(object):
... def __init__(self, request):
... self.request = request
...
... def __call__(self):
... return '/@@/resource.js'
>>> zope.component.provideAdapter(
... JSResource,
... (IDefaultBrowserLayer,),
... zope.interface.Interface, name='resource.js')
>>> JSViewlet = viewlet.JavaScriptViewlet('resource.js')
>>> print JSViewlet(content, request, view, manager).render().strip()
<script type="text/javascript" src="/@@/resource.js"></script>
There is also a javascript viewlet base class which knows how to render more
then one javascript resource file:
>>> class JSSecondResource(object):
... def __init__(self, request):
... self.request = request
...
... def __call__(self):
... return '/@@/second-resource.js'
>>> zope.component.provideAdapter(
... JSSecondResource,
... (IDefaultBrowserLayer,),
... zope.interface.Interface, name='second-resource.js')
>>> JSBundleViewlet = viewlet.JavaScriptBundleViewlet(('resource.js',
... 'second-resource.js'))
>>> print JSBundleViewlet(content, request, view, manager).render().strip()
<script type="text/javascript"
src="/@@/resource.js"> </script>
<script type="text/javascript"
src="/@@/second-resource.js"> </script>
The same works for the CSS resource viewlet:
>>> class CSSResource(object):
... def __init__(self, request):
... self.request = request
...
... def __call__(self):
... return '/@@/resource.css'
>>> zope.component.provideAdapter(
... CSSResource,
... (IDefaultBrowserLayer,),
... zope.interface.Interface, name='resource.css')
>>> CSSViewlet = viewlet.CSSViewlet('resource.css')
>>> print CSSViewlet(content, request, view, manager).render().strip()
<link type="text/css" rel="stylesheet"
href="/@@/resource.css" media="all" />
You can also change the media type and the rel attribute:
>>> CSSViewlet = viewlet.CSSViewlet('resource.css', media='print', rel='css')
>>> print CSSViewlet(content, request, view, manager).render().strip()
<link type="text/css" rel="css" href="/@@/resource.css"
media="print" />
There is also a bundle viewlet for CSS links:
>>> class CSSPrintResource(object):
... def __init__(self, request):
... self.request = request
...
... def __call__(self):
... return '/@@/print-resource.css'
>>> zope.component.provideAdapter(
... CSSPrintResource,
... (IDefaultBrowserLayer,),
... zope.interface.Interface, name='print-resource.css')
>>> items = []
>>> items.append({'path':'resource.css', 'rel':'stylesheet', 'media':'all'})
>>> items.append({'path':'print-resource.css', 'media':'print'})
>>> CSSBundleViewlet = viewlet.CSSBundleViewlet(items)
>>> print CSSBundleViewlet(content, request, view, manager).render().strip()
<link type="text/css" rel="stylesheet"
href="/@@/resource.css" media="all" />
<link type="text/css" rel="stylesheet"
href="/@@/print-resource.css" media="print" />
A Complex Example
-----------------
The Data
~~~~~~~~
So far we have only demonstrated simple (maybe overly trivial) use cases of
the viewlet system. In the following example, we are going to develop a
generic contents view for files. The step is to create a file component:
>>> class IFile(zope.interface.Interface):
... data = zope.interface.Attribute('Data of file.')
>>> class File(object):
... zope.interface.implements(IFile)
... def __init__(self, data=''):
... self.__name__ = ''
... self.data = data
Since we want to also provide the size of a file, here a simple implementation
of the ``ISized`` interface:
>>> from zope import size
>>> class FileSized(object):
... zope.interface.implements(size.interfaces.ISized)
... zope.component.adapts(IFile)
...
... def __init__(self, file):
... self.file = file
...
... def sizeForSorting(self):
... return 'byte', len(self.file.data)
...
... def sizeForDisplay(self):
... return '%i bytes' %len(self.file.data)
>>> zope.component.provideAdapter(FileSized)
We also need a container to which we can add files:
>>> class Container(dict):
... def __setitem__(self, name, value):
... value.__name__ = name
... super(Container, self).__setitem__(name, value)
Here is some sample data:
>>> container = Container()
>>> container['test.txt'] = File('Hello World!')
>>> container['mypage.html'] = File('<html><body>Hello World!</body></html>')
>>> container['data.xml'] = File('<message>Hello World!</message>')
The View
~~~~~~~~
The contents view of the container should iterate through the container and
represent the files in a table:
>>> contentsTemplate = os.path.join(temp_dir, 'contents.pt')
>>> open(contentsTemplate, 'w').write('''
... <html>
... <body>
... <h1>Contents</h1>
... <div tal:content="structure provider:contents" />
... </body>
... </html>
... ''')
>>> from zope.browserpage.simpleviewclass import SimpleViewClass
>>> Contents = SimpleViewClass(contentsTemplate, name='contents.html')
The Viewlet Manager
~~~~~~~~~~~~~~~~~~~
Now we have to write our own viewlet manager. In this case we cannot use the
default implementation, since the viewlets will be looked up for each
different item:
>>> shownColumns = []
>>> class ContentsViewletManager(object):
... zope.interface.implements(interfaces.IViewletManager)
... index = None
...
... def __init__(self, context, request, view):
... self.context = context
... self.request = request
... self.__parent__ = view
...
... def update(self):
... rows = []
... for name, value in self.context.items():
... rows.append(
... [zope.component.getMultiAdapter(
... (value, self.request, self.__parent__, self),
... interfaces.IViewlet, name=colname)
... for colname in shownColumns])
... [entry.update() for entry in rows[-1]]
... self.rows = rows
...
... def render(self, *args, **kw):
... return self.index(*args, **kw)
Now we need a template to produce the contents table:
>>> tableTemplate = os.path.join(temp_dir, 'table.pt')
>>> open(tableTemplate, 'w').write('''
... <table>
... <tr tal:repeat="row view/rows">
... <td tal:repeat="column row">
... <tal:block replace="structure column/render" />
... </td>
... </tr>
... </table>
... ''')
From the two pieces above, we can generate the final viewlet manager class and
register it (it's a bit tedious, I know):
>>> from zope.browserpage import ViewPageTemplateFile
>>> ContentsViewletManager = type(
... 'ContentsViewletManager', (ContentsViewletManager,),
... {'index': ViewPageTemplateFile(tableTemplate)})
>>> zope.component.provideAdapter(
... ContentsViewletManager,
... (Container, IDefaultBrowserLayer, zope.interface.Interface),
... interfaces.IViewletManager, name='contents')
Since we have not defined any viewlets yet, the table is totally empty:
>>> contents = Contents(container, request)
>>> print contents().strip()
<html>
<body>
<h1>Contents</h1>
<div>
<table>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</div>
</body>
</html>
The Viewlets and the Final Result
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now let's create a first viewlet for the manager...
>>> class NameViewlet(object):
...
... def __init__(self, context, request, view, manager):
... self.__parent__ = view
... self.context = context
...
... def update(self):
... pass
...
... def render(self):
... return self.context.__name__
and register it:
>>> zope.component.provideAdapter(
... NameViewlet,
... (IFile, IDefaultBrowserLayer,
... zope.interface.Interface, interfaces.IViewletManager),
... interfaces.IViewlet, name='name')
Note how you register the viewlet on ``IFile`` and not on the container. Now
we should be able to see the name for each file in the container:
>>> print contents().strip()
<html>
<body>
<h1>Contents</h1>
<div>
<table>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</div>
</body>
</html>
Waaa, nothing there! What happened? Well, we have to tell our user preferences
that we want to see the name as a column in the table:
>>> shownColumns = ['name']
>>> print contents().strip()
<html>
<body>
<h1>Contents</h1>
<div>
<table>
<tr>
<td>
mypage.html
</td>
</tr>
<tr>
<td>
data.xml
</td>
</tr>
<tr>
<td>
test.txt
</td>
</tr>
</table>
</div>
</body>
</html>
Let's now write a second viewlet that will display the size of the object for
us:
>>> class SizeViewlet(object):
...
... def __init__(self, context, request, view, manager):
... self.__parent__ = view
... self.context = context
...
... def update(self):
... pass
...
... def render(self):
... return size.interfaces.ISized(self.context).sizeForDisplay()
>>> zope.component.provideAdapter(
... SizeViewlet,
... (IFile, IDefaultBrowserLayer,
... zope.interface.Interface, interfaces.IViewletManager),
... interfaces.IViewlet, name='size')
After we added it to the list of shown columns,
>>> shownColumns = ['name', 'size']
we can see an entry for it:
>>> print contents().strip()
<html>
<body>
<h1>Contents</h1>
<div>
<table>
<tr>
<td>
mypage.html
</td>
<td>
38 bytes
</td>
</tr>
<tr>
<td>
data.xml
</td>
<td>
31 bytes
</td>
</tr>
<tr>
<td>
test.txt
</td>
<td>
12 bytes
</td>
</tr>
</table>
</div>
</body>
</html>
If we switch the two columns around,
>>> shownColumns = ['size', 'name']
the result will be
>>> print contents().strip()
<html>
<body>
<h1>Contents</h1>
<div>
<table>
<tr>
<td>
38 bytes
</td>
<td>
mypage.html
</td>
</tr>
<tr>
<td>
31 bytes
</td>
<td>
data.xml
</td>
</tr>
<tr>
<td>
12 bytes
</td>
<td>
test.txt
</td>
</tr>
</table>
</div>
</body>
</html>
Supporting Sorting
~~~~~~~~~~~~~~~~~~
Oftentimes you also want to batch and sort the entries in a table. Since those
two features are not part of the view logic, they should be treated with
independent components. In this example, we are going to only implement
sorting using a simple utility:
>>> class ISorter(zope.interface.Interface):
...
... def sort(values):
... """Sort the values."""
>>> class SortByName(object):
... zope.interface.implements(ISorter)
...
... def sort(self, values):
... return sorted(values, lambda x, y: cmp(x.__name__, y.__name__))
>>> zope.component.provideUtility(SortByName(), name='name')
>>> class SortBySize(object):
... zope.interface.implements(ISorter)
...
... def sort(self, values):
... return sorted(
... values,
... lambda x, y: cmp(size.interfaces.ISized(x).sizeForSorting(),
... size.interfaces.ISized(y).sizeForSorting()))
>>> zope.component.provideUtility(SortBySize(), name='size')
Note that we decided to give the sorter utilities the same name as the
corresponding viewlet. This convention will make our implementation of the
viewlet manager much simpler:
>>> sortByColumn = ''
>>> class SortedContentsViewletManager(object):
... zope.interface.implements(interfaces.IViewletManager)
... index = None
...
... def __init__(self, context, request, view):
... self.context = context
... self.request = request
... self.__parent__ = view
...
... def update(self):
... values = self.context.values()
...
... if sortByColumn:
... sorter = zope.component.queryUtility(ISorter, sortByColumn)
... if sorter:
... values = sorter.sort(values)
...
... rows = []
... for value in values:
... rows.append(
... [zope.component.getMultiAdapter(
... (value, self.request, self.__parent__, self),
... interfaces.IViewlet, name=colname)
... for colname in shownColumns])
... [entry.update() for entry in rows[-1]]
... self.rows = rows
...
... def render(self, *args, **kw):
... return self.index(*args, **kw)
As you can see, the concern of sorting is cleanly separated from generating
the view code. In MVC terms that means that the controller (sort) is logically
separated from the view (viewlets). Let's now do the registration dance for
the new viewlet manager. We simply override the existing registration:
>>> SortedContentsViewletManager = type(
... 'SortedContentsViewletManager', (SortedContentsViewletManager,),
... {'index': ViewPageTemplateFile(tableTemplate)})
>>> zope.component.provideAdapter(
... SortedContentsViewletManager,
... (Container, IDefaultBrowserLayer, zope.interface.Interface),
... interfaces.IViewletManager, name='contents')
Finally we sort the contents by name:
>>> shownColumns = ['name', 'size']
>>> sortByColumn = 'name'
>>> print contents().strip()
<html>
<body>
<h1>Contents</h1>
<div>
<table>
<tr>
<td>
data.xml
</td>
<td>
31 bytes
</td>
</tr>
<tr>
<td>
mypage.html
</td>
<td>
38 bytes
</td>
</tr>
<tr>
<td>
test.txt
</td>
<td>
12 bytes
</td>
</tr>
</table>
</div>
</body>
</html>
Now let's sort by size:
>>> sortByColumn = 'size'
>>> print contents().strip()
<html>
<body>
<h1>Contents</h1>
<div>
<table>
<tr>
<td>
test.txt
</td>
<td>
12 bytes
</td>
</tr>
<tr>
<td>
data.xml
</td>
<td>
31 bytes
</td>
</tr>
<tr>
<td>
mypage.html
</td>
<td>
38 bytes
</td>
</tr>
</table>
</div>
</body>
</html>
That's it! As you can see, in a few steps we have built a pretty flexible
contents view with selectable columns and sorting. However, there is a lot of
room for extending this example:
- Table Header: The table header cell for each column should be a different
type of viewlet, but registered under the same name. The column header
viewlet also adapts the container not the item. The header column should
also be able to control the sorting.
- Batching: A simple implementation of batching should work very similar to
the sorting feature. Of course, efficient implementations should somehow
combine batching and sorting more effectively.
- Sorting in ascending and descending order: Currently, you can only sort from
the smallest to the highest value; however, this limitation is almost
superficial and can easily be removed by making the sorters a bit more
flexible.
- Further Columns: For a real application, you would want to implement other
columns, of course. You would also probably want some sort of fallback for
the case that a viewlet is not found for a particular container item and
column.
Cleanup
-------
>>> import shutil
>>> shutil.rmtree(temp_dir)
================================
The ``viewletManager`` Directive
================================
The ``viewletManager`` directive allows you to quickly register a new viewlet
manager without worrying about the details of the ``adapter``
directive. Before we can use the directives, we have to register their
handlers by executing the package's meta configuration:
>>> from zope.configuration import xmlconfig
>>> context = xmlconfig.string('''
... <configure i18n_domain="zope">
... <include package="zope.viewlet" file="meta.zcml" />
... </configure>
... ''')
Now we can register a viewlet manager:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewletManager
... name="defaultmanager"
... permission="zope.Public"
... />
... </configure>
... ''', context=context)
Let's make sure the directive has really issued a sensible adapter
registration; to do that, we create some dummy content, request and view
objects:
>>> import zope.interface
>>> class Content(object):
... zope.interface.implements(zope.interface.Interface)
>>> content = Content()
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> from zope.publisher.browser import BrowserView
>>> view = BrowserView(content, request)
Now let's lookup the manager. This particular registration is pretty boring:
>>> import zope.component
>>> from zope.viewlet import interfaces
>>> manager = zope.component.getMultiAdapter(
... (content, request, view),
... interfaces.IViewletManager, name='defaultmanager')
>>> manager
<zope.viewlet.manager.<ViewletManager providing IViewletManager> object ...>
>>> interfaces.IViewletManager.providedBy(manager)
True
>>> manager.template is None
True
>>> manager.update()
>>> manager.render()
u''
However, this registration is not very useful, since we did specify a specific
viewlet manager interface, a specific content interface, specific view or
specific layer. This means that all viewlets registered will be found.
The first step to effectively using the viewlet manager directive is to define
a special viewlet manager interface:
>>> class ILeftColumn(interfaces.IViewletManager):
... """Left column of my page."""
Now we can register register a manager providing this interface:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewletManager
... name="leftcolumn"
... permission="zope.Public"
... provides="zope.viewlet.directives.ILeftColumn"
... />
... </configure>
... ''', context=context)
>>> manager = zope.component.getMultiAdapter(
... (content, request, view), ILeftColumn, name='leftcolumn')
>>> manager
<zope.viewlet.manager.<ViewletManager providing ILeftColumn> object ...>
>>> ILeftColumn.providedBy(manager)
True
>>> manager.template is None
True
>>> manager.update()
>>> manager.render()
u''
Next let's see what happens, if we specify a template for the viewlet manager:
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> leftColumnTemplate = os.path.join(temp_dir, 'leftcolumn.pt')
>>> open(leftColumnTemplate, 'w').write('''
... <div class="column">
... <div class="entry"
... tal:repeat="viewlet options/viewlets"
... tal:content="structure viewlet" />
... </div>
... ''')
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewletManager
... name="leftcolumn"
... permission="zope.Public"
... provides="zope.viewlet.directives.ILeftColumn"
... template="%s"
... />
... </configure>
... ''' %leftColumnTemplate, context=context)
>>> manager = zope.component.getMultiAdapter(
... (content, request, view), ILeftColumn, name='leftcolumn')
>>> manager
<zope.viewlet.manager.<ViewletManager providing ILeftColumn> object ...>
>>> ILeftColumn.providedBy(manager)
True
>>> manager.template
<BoundPageTemplateFile of ...<ViewletManager providing ILeftColumn> ...>>
>>> manager.update()
>>> print manager.render().strip()
<div class="column">
</div>
Additionally you can specify a class that will serve as a base to the default
viewlet manager or be a viewlet manager in its own right. In our case we will
provide a custom implementation of the ``sort()`` method, which will sort by a
weight attribute in the viewlet:
>>> class WeightBasedSorting(object):
... def sort(self, viewlets):
... return sorted(viewlets,
... lambda x, y: cmp(x[1].weight, y[1].weight))
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewletManager
... name="leftcolumn"
... permission="zope.Public"
... provides="zope.viewlet.directives.ILeftColumn"
... template="%s"
... class="zope.viewlet.directives.WeightBasedSorting"
... />
... </configure>
... ''' %leftColumnTemplate, context=context)
>>> manager = zope.component.getMultiAdapter(
... (content, request, view), ILeftColumn, name='leftcolumn')
>>> manager
<zope.viewlet.manager.<ViewletManager providing ILeftColumn> object ...>
>>> manager.__class__.__bases__
(<class 'zope.viewlet.directives.WeightBasedSorting'>,
<class 'zope.viewlet.manager.ViewletManagerBase'>)
>>> ILeftColumn.providedBy(manager)
True
>>> manager.template
<BoundPageTemplateFile of ...<ViewletManager providing ILeftColumn> ...>>
>>> manager.update()
>>> print manager.render().strip()
<div class="column">
</div>
Finally, if a non-existent template is specified, an error is raised:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewletManager
... name="leftcolumn"
... permission="zope.Public"
... template="foo.pt"
... />
... </configure>
... ''', context=context)
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "<string>", line 3.2-7.8
ConfigurationError: ('No such file', '...foo.pt')
=========================
The ``viewlet`` Directive
=========================
Now that we have a viewlet manager, we have to register some viewlets for
it. The ``viewlet`` directive is similar to the ``viewletManager`` directive,
except that the viewlet is also registered for a particular manager interface,
as seen below:
>>> weatherTemplate = os.path.join(temp_dir, 'weather.pt')
>>> open(weatherTemplate, 'w').write('''
... <div>sunny</div>
... ''')
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewlet
... name="weather"
... manager="zope.viewlet.directives.ILeftColumn"
... template="%s"
... permission="zope.Public"
... extra_string_attributes="can be specified"
... />
... </configure>
... ''' % weatherTemplate, context=context)
If we look into the adapter registry, we will find the viewlet:
>>> viewlet = zope.component.getMultiAdapter(
... (content, request, view, manager), interfaces.IViewlet,
... name='weather')
>>> viewlet.render().strip()
u'<div>sunny</div>'
>>> viewlet.extra_string_attributes
u'can be specified'
The manager now also gives us the output of the one and only viewlet:
>>> manager.update()
>>> print manager.render().strip()
<div class="column">
<div class="entry">
<div>sunny</div>
</div>
</div>
Let's now ensure that we can also specify a viewlet class:
>>> class Weather(object):
... weight = 0
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewlet
... name="weather2"
... for="*"
... manager="zope.viewlet.directives.ILeftColumn"
... template="%s"
... class="zope.viewlet.directives.Weather"
... permission="zope.Public"
... />
... </configure>
... ''' % weatherTemplate, context=context)
>>> viewlet = zope.component.getMultiAdapter(
... (content, request, view, manager), interfaces.IViewlet,
... name='weather2')
>>> viewlet().strip()
u'<div>sunny</div>'
Okay, so the template-driven cases work. But just specifying a class should
also work:
>>> class Sport(object):
... weight = 0
... def __call__(self):
... return u'Red Sox vs. White Sox'
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewlet
... name="sport"
... for="*"
... manager="zope.viewlet.directives.ILeftColumn"
... class="zope.viewlet.directives.Sport"
... permission="zope.Public"
... />
... </configure>
... ''', context=context)
>>> viewlet = zope.component.getMultiAdapter(
... (content, request, view, manager), interfaces.IViewlet, name='sport')
>>> viewlet()
u'Red Sox vs. White Sox'
It should also be possible to specify an alternative attribute of the class to
be rendered upon calling the viewlet:
>>> class Stock(object):
... weight = 0
... def getStockTicker(self):
... return u'SRC $5.19'
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewlet
... name="stock"
... for="*"
... manager="zope.viewlet.directives.ILeftColumn"
... class="zope.viewlet.directives.Stock"
... attribute="getStockTicker"
... permission="zope.Public"
... />
... </configure>
... ''', context=context)
>>> viewlet = zope.component.getMultiAdapter(
... (content, request, view, manager), interfaces.IViewlet,
... name='stock')
>>> viewlet.render()
u'SRC $5.19'
A final feature the ``viewlet`` directive is that it supports the
specification of any number of keyword arguments:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewlet
... name="stock2"
... permission="zope.Public"
... class="zope.viewlet.directives.Stock"
... weight="8"
... />
... </configure>
... ''', context=context)
>>> viewlet = zope.component.getMultiAdapter(
... (content, request, view, manager), interfaces.IViewlet,
... name='stock2')
>>> viewlet.weight
u'8'
Error Scenarios
---------------
Neither the class or template have been specified:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewlet
... name="testviewlet"
... manager="zope.viewlet.directives.ILeftColumn"
... permission="zope.Public"
... />
... </configure>
... ''', context=context)
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "<string>", line 3.2-7.8
ConfigurationError: Must specify a class or template
The specified attribute is not ``__call__``, but also a template has been
specified:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewlet
... name="testviewlet"
... manager="zope.viewlet.directives.ILeftColumn"
... template="test_viewlet.pt"
... attribute="faux"
... permission="zope.Public"
... />
... </configure>
... ''', context=context)
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "<string>", line 3.2-9.8
ConfigurationError: Attribute and template cannot be used together.
Now, we are not specifying a template, but a class that does not have the
specified attribute:
>>> context = xmlconfig.string('''
... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope">
... <viewlet
... name="testviewlet"
... manager="zope.viewlet.directives.ILeftColumn"
... class="zope.viewlet.directives.Sport"
... attribute="faux"
... permission="zope.Public"
... />
... </configure>
... ''', context=context)
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "<string>", line 3.2-9.8
ConfigurationError: The provided class doesn't have the specified attribute
Cleanup
-------
>>> import shutil
>>> shutil.rmtree(temp_dir)
=======
CHANGES
=======
3.7.2 (2010-05-25)
------------------
- Fixed unit tests broken under Python 2.4 by the switch to the standard
library ``doctest`` module.
3.7.1 (2010-04-30)
------------------
- Removed use of 'zope.testing.doctest' in favor of stdlib's 'doctest.
- Fixed dubious quoting in metadirectives.py. Closes
https://bugs.launchpad.net/zope2/+bug/143774.
3.7.0 (2009-12-22)
------------------
- Depend on zope.browserpage in favor of zope.app.pagetemplate.
3.6.1 (2009-08-29)
------------------
- Fixed unit tests in README.txt.
3.6.0 (2009-08-02)
------------------
- Optimize the the script tag for the JS viewlet. This makes YSlow happy.
- Remove ZCML slugs and old zpkg-related files.
- Drop all testing dependncies except ``zope.testing``.
3.5.0 (2009-01-26)
------------------
- Removed the dependency on `zope.app.publisher` by moving four simple helper
functions into this package and making the interface for describing the
ZCML content provider directive explicit.
- Typo fix in CSSViewlet docstring.
3.4.2 (2008-01-24)
------------------
- Re-release of 3.4.1 because of brown bag release.
3.4.1 (2008-01-21)
------------------
- bugfix, implemented missing __contains__ method in IViewletManager
- implemented additional viewlet managers offering weight ordered sorting
- implemented additional viewlet managers offering conditional filtering
3.4.1a (2007-4-22)
------------------
- bugfix, added a missing ',' behind zope.i18nmessageid.
- recreated the README.txt removing everything except for the overview.
3.4.0 (2007-10-10)
------------------
- Initial release independent of the main Zope tree.
Keywords: zope web html ui viewlet pattern
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Zope Public License
Classifier: Programming Language :: Python
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Framework :: Zope3
|