As much as WordPress is a code disaster, there are still a few good practices and lessons that can be learned from it. One of those practices that I've come to appreciate is the idea of a "slug", which is basically a URL, DOM ID and database key-friendly field in a table.
So for example, if you have a Products table with a product number, name and description, you may find that none of these fields are appropriate to use as a DOM ID but you may need a DOM ID to do some page automation. This is a good time for a "slug"!
id slug product_number name description
-- ------- -------------- ------------ -----------
1 widgetT PN-409A 1 Widget Thing A thingy widget.
2 widgetS PN-409B 5 Widget Stuff Stuff for a widget.
Now we have a unique, DOM-friendly ID that we can use in our HTML:
<a href="#" id="{{ $product->slug }}" onClick="addProduct({{ $product->slug }}">
<script>
function addProduct(slug) {
$('#' + slug).css('color', '#ccc');
}
</script>
I find this to be a lot cleaner and intutive than:
<a href="#" id="product{{ $product->id }}" onClick="addProduct({{ $product->id }}">
<script>
function addProduct(pid) {
$('#product' + id).css('color', '#ccc');
}
</script>
If you ever look at the page source, it is handy to have the ID indicate the actual product.
Plus, you can use that slug for more SEO-friendly URLs:
<a href="/product/{{ $product->slug }}">
Result: http://www.mysite.com/product/widgetT
So for example, if you have a Products table with a product number, name and description, you may find that none of these fields are appropriate to use as a DOM ID but you may need a DOM ID to do some page automation. This is a good time for a "slug"!
id slug product_number name description
-- ------- -------------- ------------ -----------
1 widgetT PN-409A 1 Widget Thing A thingy widget.
2 widgetS PN-409B 5 Widget Stuff Stuff for a widget.
3 thingyN TH-655Z ABC Non-widget Thing Thing with no widget.
Now we have a unique, DOM-friendly ID that we can use in our HTML:
<a href="#" id="{{ $product->slug }}" onClick="addProduct({{ $product->slug }}">
<script>
function addProduct(slug) {
$('#' + slug).css('color', '#ccc');
}
</script>
I find this to be a lot cleaner and intutive than:
<a href="#" id="product{{ $product->id }}" onClick="addProduct({{ $product->id }}">
<script>
function addProduct(pid) {
$('#product' + id).css('color', '#ccc');
}
</script>
If you ever look at the page source, it is handy to have the ID indicate the actual product.
Plus, you can use that slug for more SEO-friendly URLs:
<a href="/product/{{ $product->slug }}">
Result: http://www.mysite.com/product/widgetT
Comments
Post a Comment