ParserFunctions
- ParserFunctions
ParserFunctions are a powerful extension to the MediaWiki markup language that allow you to perform calculations, string manipulation, and conditional logic directly within your wiki pages. They provide a way to create dynamic content without needing to resort to complex template coding or server-side scripting. This article serves as a comprehensive guide to ParserFunctions, geared towards beginners, covering their core functionalities and demonstrating their practical applications. Understanding ParserFunctions unlocks a significant level of flexibility and sophistication in how you present information on your wiki. This is especially useful in creating dynamic tables, calculating values, and implementing advanced page features.
What are ParserFunctions?
Essentially, ParserFunctions are built-in functions that you can embed within wiki text using the `{{#function: ... }}` syntax. The text inside the function call is then processed, and the result replaces the entire function call within the page. These functions operate on text strings and numbers, offering a range of operations from simple string manipulation to relatively complex logical evaluations. They are evaluated during the page rendering process, meaning the output you see is determined *when the page is viewed*, not when it is saved.
ParserFunctions are *not* a programming language in the full sense. They lack concepts like variables (beyond function arguments), loops, or complex data structures. However, their capabilities are surprisingly extensive and sufficient for many common tasks within a wiki environment. They are often used to enhance Templates and create more interactive content.
Core ParserFunctions
Here's a breakdown of the most commonly used ParserFunctions, with examples:
- **`#if:` (Conditional Expression)**: This function evaluates a condition and displays different content depending on whether the condition is true or false.
Syntax: `{{#if: condition | then | else}}`
Example: `{{#if: {{#time:Y}} > 2023 | This year is after 2023 | This year is 2023 or earlier}}` This will display "This year is after 2023" if the current year is greater than 2023, and "This year is 2023 or earlier" otherwise. This is useful for displaying content based on the current date or other dynamic conditions.
- **`#ifeq:` (Equality Check)**: Checks if two values are equal.
Syntax: `{{#ifeq: value1 | value2 | then | else}}`
Example: `{{#ifeq: ParserFunctions | ParserFunctions | This is the ParserFunctions page! | This is not the ParserFunctions page.}}` This will display "This is the ParserFunctions page!" if the current page title is "ParserFunctions", and "This is not the ParserFunctions page." otherwise. This is often used to customize content based on the page being viewed.
- **`#ifneq:` (Inequality Check)**: Checks if two values are *not* equal.
Syntax: `{{#ifneq: value1 | value2 | then | else}}`
Example: `{{#ifneq: {{#time:d}} | 01 | Not the first day of the month | It's the first day of the month!}}` This displays different messages depending on whether the current day of the month is the 1st.
- **`#switch:` (Multiple Conditionals)**: Allows checking a value against multiple possible cases.
Syntax: `{{#switch: value | case1 | result1 | case2 | result2 | ... | default}}`
Example: `{{#switch: parserfunctions | parserfunctions | This page discusses ParserFunctions. | templates | This page relates to Templates. | main_page | Welcome to the Main Page! | #default | Unknown page.}}` This checks the lowercase page name and displays a corresponding message. The `#default` case is displayed if none of the other cases match.
- **`#vardefine:` (Variable Definition)**: Defines a named variable that can be used within the current page. *Important:* Variables defined with `#vardefine` are only available within the *same* ParserFunction call chain.
Syntax: `{{#vardefine: variable_name | value}}`
Example: `{{#vardefine: my_number | 10 }}{{#expr: Template:My number + 5}}` displays 15.
- **`#varbyname:` (Variable Access)**: Accesses a variable defined using `#vardefine`.
Syntax: `{{#varbyname: variable_name}}`
Example: Following the example above, `The value of my_number is: {{#varbyname: my_number}}` would display "The value of my_number is: 10".
- **`#expr:` (Mathematical Expression)**: Evaluates a mathematical expression.
Syntax: `{{#expr: expression}}`
Example: `{{#expr: 2 + 3 * 4}}` evaluates to 14. Supports basic arithmetic operations (+, -, *, /, %). This is incredibly useful for calculations within tables, such as calculating percentages or running totals. See Technical Analysis for examples of numerical calculations.
- **`#time:` (Date and Time Formatting)**: Formats the current date and time.
Syntax: `{{#time: format}}`
Example: `{{#time: Y-m-d}}` displays the current date in the format "YYYY-MM-DD". Numerous format options are available (see MediaWiki documentation for a complete list). This is essential for displaying dynamic dates, such as last updated timestamps or event dates. Understanding Trend Analysis often relies on time-based data.
- **`#title:` (Page Title Manipulation)**: Processes a page title.
Syntax: `{{#title: page title}}`
Example: `{{#title: ParserFunctions|urlencode}}` will URL-encode the title "ParserFunctions".
- **`#property:` (Property Access)**: Retrieves a property of a page.
Syntax: `{{#property: page title | property name}}`
Example: `{{#property: Main Page | featured}}` will retrieve the "featured" property of the Main Page.
- **`#ask:` (Semantic Web Integration)**: Queries a semantic database for information. Requires the Semantic MediaWiki extension. This is a very powerful function for creating dynamic lists and reports based on structured data. It's a cornerstone of building knowledge bases and data-driven wikis.
Advanced Techniques and Considerations
- **Nesting ParserFunctions:** You can nest ParserFunctions within each other to create complex logic. However, be mindful of readability and performance. Excessive nesting can make code difficult to understand and slow down page rendering.
- **String Manipulation:** While ParserFunctions don't have dedicated string manipulation functions like `substring` or `replace`, you can often achieve similar results by combining `#if`, `#ifeq`, and `#switch` with string concatenation.
- **Escaping Characters:** Pay attention to escaping special characters within ParserFunction arguments. For example, if you want to include a pipe symbol (|) within a `#switch` case, you need to escape it using `|`.
- **Performance:** ParserFunctions can be computationally expensive, especially when used heavily on high-traffic pages. Avoid using them unnecessarily and optimize your code for performance. Consider using templates or server-side scripting for complex tasks that are beyond the capabilities of ParserFunctions.
- **Limitations:** ParserFunctions have limitations. They cannot access external data sources directly, and they have limited memory and processing power. They are best suited for relatively simple tasks that can be performed within the wiki environment. For more complex tasks, consider using extensions like Lua scripting.
- **Error Handling:** ParserFunctions don't provide robust error handling. If an error occurs during evaluation, the function will typically return an error message, which can disrupt the page layout. Carefully test your code to ensure it handles potential errors gracefully.
Practical Examples
Let's look at some practical examples of how ParserFunctions can be used:
1. **Dynamic Table Calculation:** Create a table showing the projected growth of an investment over time. Use `#expr` to calculate the future value based on the initial investment, interest rate, and number of years.
2. **Conditional Formatting:** Highlight table rows based on certain criteria. Use `#if` or `#ifeq` to check the value of a cell and apply different formatting accordingly. This is useful for indicating whether a Support and Resistance Level has been breached.
3. **Dynamic Content Based on Category Membership:** Display different information based on whether a page belongs to a specific category. Use `#if` in conjunction with category detection mechanisms (often implemented through templates or extensions).
4. **Creating Dynamic Lists:** Use `#switch` to create lists of items based on a selected option. This is useful for creating menus or navigation bars. Consider this within the context of Fibonacci Retracements.
5. **Date-Based Notifications:** Display a message if a page hasn't been updated in a certain amount of time. Use `#time` to calculate the difference between the current date and the page's last modified date.
6. **Calculating Risk-Reward Ratio:** Using `#expr` and variables, calculate the risk-reward ratio of a trade given the entry price, stop-loss price, and take-profit price. This is fundamental to Risk Management.
7. **Determining Trend Direction:** Use `#if` to determine the trend direction based on a moving average crossover. This requires integrating with other wiki content that provides the moving average values. Consider integrating with [[Moving Average Convergence Divergence (MACD)].
8. **Displaying Volatility:** Incorporate calculations using `#expr` to present the Average True Range (ATR) or other volatility indicators.
9. **Calculating Position Size:** Employ `#expr` to determine the appropriate position size based on risk tolerance, account balance, and stop-loss distance. This is a critical element of Position Sizing.
10. **Showing Correlation:** Integrate data to display the correlation between different assets using calculations with `#expr`. This is a key concept in Portfolio Diversification.
Resources and Further Learning
- **MediaWiki ParserFunctions Documentation:** [1]
- **Semantic MediaWiki:** [2] (For `#ask` and semantic data integration)
- **Help:Templates:** Help:Templates (Understanding how ParserFunctions interact with Templates)
- **Help:Variables:** Help:Variables (Understanding variable scope and usage)
- **Help:Categories:** Help:Categories (Using categories to trigger conditional content)
- **Technical Analysis:** Technical Analysis
- **Trend Analysis:** Trend Analysis
- **Risk Management:** Risk Management
- **Position Sizing:** Position Sizing
- **Support and Resistance Level:** Support and Resistance Level
- **Fibonacci Retracements:** Fibonacci Retracements
- **Moving Average Convergence Divergence (MACD):** Moving Average Convergence Divergence (MACD)
- **Average True Range (ATR):** Average True Range (ATR)
- **Portfolio Diversification:** Portfolio Diversification
- **Bollinger Bands:** [3]
- **Relative Strength Index (RSI):** [4]
- **Stochastic Oscillator:** [5]
- **Elliott Wave Theory:** [6]
- **Candlestick Patterns:** [7]
- **Head and Shoulders Pattern:** [8]
- **Double Top/Bottom:** [9]
- **Moving Averages:** [10]
- **Volume Weighted Average Price (VWAP):** [11]
- **Ichimoku Cloud:** [12]
- **Parabolic SAR:** [13]
- **Donchian Channels:** [14]
- **Harmonic Patterns:** [15]
- **Market Sentiment:** [16]
- **Bearish Reversal Patterns:** [17]
- **Bullish Reversal Patterns:** [18]