|
Creating custom functions
A problem I have is that I have a lot of code doing the same thing. Recently,
on a project I was doing, the URL's had to be encoded to make them more friendly.
It looked something like this:
lcase(Replace(url, " ", "-"))
This would change a URL such as
/Books/This Book Title/
Into:
/books/this-book-title/
The problem is that this had to be done a dozen times in the script. At every
point I wanted to do this, I had to include the same code over again. And then
I ran into the problem of wanting to do more encoding. This mean't I had to
change every instance of the code.
The solution to this? Create a custom function. This can be put at the top
of a page of code and can then be called from anywhere else on the page. Here
is an example function:
Function Encode(url)
url = Replace(url, " ", "-")
url = lcase(url)
Encode = url
End Function
The basic syntax of a function is pretty simple. It starts with a declaration
that this is a function then it is followed by the name of function, in this
instance, I called it Encode. This is followed by the varies required for the
function.
Here the variable is url but you can have as many as you need by stacking them
up, such as:
Encode(var1, var2, var3)
The middle section is the actual processing, where the URL is encoded. The
bottom bit of this is setting the end result. This is what will be passed back
to where it was called from. Finally the function is ended.
Now you have your function, lets actually use it. Before the code would like:
<%
theurl = "/Books/This Book Title"
%>
<a href="<%=(lcase(Replace(theurl, " ", "-")))%>">Some
link</a>
But now we can replace it with our little function:
<%
theurl = "/Books/This Book Title"
%>
<a href="<%=(Encode(theurl))%>">Some link</a>
And it will end up with the same result as before. But with less redundant
code.
|